我不乏向 Node js 服务器发送 POST 请求。我有一个简单的请求和一个简单的服务器。
我的服务器代码是:
var http = require('http');
var bodyParser = require('body-parser');
http.createServer(function (req, res) {
console.log(req.body);
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/')
我的客户请求代码是:
var val = JSON.stringify({ city:"SomeCity", name:"MyNameIsHere" });
alert(val);
$.ajax({
url: 'http://127.0.0.1:1337',
type: 'POST',
data: { value: val},
success: function(result) {
alert('the request was successfully sent to the server');}
});
所以我想在 Node js 服务器的请求正文中获取 SomeCity 和 MyNameIsHere 字符串,但 req.body 字段未定义。不得不说,我用这样的 URL 在本地打开带有请求代码的 test.html:
file:///D:/Projects/test.html
可能是我瞎了,监督了一些微不足道的事情,但我不知道是什么:)
最佳答案
Have to say that I open my test.html with request code locally with URL like this:
file:///D:/Projects/test.html
您正在尝试跨域发布,在这种情况下您不能这样做。通过 HTTP 提供您的 HTML,以便您可以进行 POST。如果您使用浏览器的开发工具,您会发现该请求永远不会到达您的 Node.js 服务器(除了可能的 CORS 飞行前请求)。
另一个问题是您实际上并没有使用body-parser
。如果你想要发布数据,你必须像流一样从 req
中读取。
关于node.js - Node JS : Where is my POST data?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25141486/