如下所示
user.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);
console.log(post);
console.log(post.name)
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.username);
})
if (post.name == str.username && post.password == str.password) {
str = {
"code": '1',
"message": "ok"
};
res.write(String(str));
} else {
str = {
"code": '0',
"message": '用户名或密码不正确'
};
res.write(String(str));
}
// 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: 'wuyu',
password: '123456'
},
dataType: "json",
success: function (data) {
$('body').html(`<h1>${data.username}</h1>`);
},
error: function (e) {
console.log(e);
}
});
</script>
</body>
</html>
跨域条件
再说你的为什么写了不管用。CORS其实是在OPTIONS的嗅探请求里面给返回的。
Access to XMLHttpRequest at 'http://127.0.0.1:3000/' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
话说这个错误重点是
from origin 'null'
吧1:换个火狐浏览器试试?

2:静态文件也部署到一个服务器
3: 你的那种方法写不上,换另一个答案的方式可以。
我express的跨域没问题。
$.ajax({url: 'https://www.lilnong.top/cors/1'})
看上去是这里覆盖了。删了就好了
