今天遇到了一个问题,一直找原因。那就是前端ajax请求,后端返回了值,是成功的。但是就是进入不了success。多方查找原因,原来是我写了dataType: “json”,而后端返回的是test,所以把json改为’test’就可以进入success了
前端代码
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<link rel='stylesheet' href='/stylesheets/style.css' />
<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
<!-- <h1><%= title %></h1>
<p>Welcome to <%= title %></p> -->
<button id="btn">点击请求</button>
</body>
<script>
$(function(){
$('#btn').click(function(){
$.ajax({
type: "get",
url: "http://localhost:3000/readfile",
data: {
url: 'C:/Users/yiqiu.guan/Desktop/新建文本文档.txt'
},
dataType: "text",
success: function(data){
console.log('data', data)
alert(data)
},
error: function(err){
console.log('err', err);
}
});
})
})
</script>
</html>
后端代码
app.get('/readfile', (req, response) => {
fs.readFile(req.query.url, 'utf8', function(err, data) {
if (err) {
console.log('err', err)
} else {
response.writeHead(200,{"Content-Type":'text/plain','charset':'utf-8','Access-Control-Allow-Origin':'*','Access-Control-Allow-Methods':'PUT,POST,GET,DELETE,OPTIONS'});//可以解决跨域的请求
response.send(data);
response.end();
}
})