模拟发送数据,服务器返回数据,但是报错,第一次接触,不造错在哪,求指教~~
server.js
var http = require("http");
var fs = require("fs");
var querystring = require('querystring');
var str = 'empty';
http.createServer(function (req, res) {
// // 定义了一个post变量,用于暂存请求体的信息
var post = '';
// // 通过req的data事件监听函数,每当接受到请求体的数据,就累加到post变量中
req.on('data', function (chunk) {
post += chunk;
})
// // 在end事件触发后,通过querystring.parse将post解析为真正的POST请求格式,然后向客户端返回。
req.on('end', function () {
post = querystring.parse(post);
res.writeHead(200, {
"Content-Type": 'application/json ',
// "Content-Type": 'text/plain ',
'charset': 'utf-8',
//可以解决跨域的请求
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild',
'Access-Control-Allow-Methods': 'PUT,POST,GET,DELETE,OPTIONS'
});
// if (!post) {
// str = fs.readFileSync('./user.json');
// } else {
str = fs.readFileSync('./user.json');
// }
console.log(str[0].username);
res.write(str);
res.end();
}).listen(3000);
})
console.log("Server has started.port on localhost:3000");
user.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
<script>
$.ajax({
url: "http://127.0.0.1:3000",
type: "POST",
data: {
name: 'admin',
password: '123456'
},
dataType: "json",
success: function (data) {
$('body').html(`<h1>${data[0].username}</h1>`);
},
error: function (e) {
console.log(e);
}
});
</script>
</body>
</html>
user.json
{
"username": "admin",
"password": "123456",
}
我也感觉是你的服务没有起来。你在node回调里面打console试试?
}).listen(3000);
这里写错了。应该是给server对象写