我需要使用 javascript 函数将数据从 HTML 表单发送到在同一地址运行的 node.js 服务器。 作为记录,我在我的 Raspberry PI 上托管了一个网站,使用自定义域。 这是 javascript 函数:
$.post("http://www.website.com:2052/form", formData, function(data){
...
console.log("POST SUCCESS");
...
});
这是我的 node.js 服务器的代码:
app.post('/form', function(req, res){
....
console.log('POST - body: ' + JSON.stringify(req.body));
res.send({result:"success"});
....
});
当我将表单数据发送到服务器时,我在服务器上收到它,但我在网站端收到:
Failed to load http://www.website.com:2052/form: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://www.website.com' is therefore not allowed access.
我知道我需要在响应中添加访问控制 header ,但考虑到它们在同一个“ip”上,为什么需要它?或者我怎样才能使 node.js 服务器实际出现在同一个域中? 谢谢
最佳答案
你应该将它添加到你的 node.js 服务器:
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
next();
});
您可以查看以下文档:
关于javascript - 网站中的javascript与node.js服务器之间的POST请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52009806/