Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/33.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 无法为Express.js应用程序(CORS)设置标题_Node.js_Express_Cors - Fatal编程技术网

Node.js 无法为Express.js应用程序(CORS)设置标题

Node.js 无法为Express.js应用程序(CORS)设置标题,node.js,express,cors,Node.js,Express,Cors,无论我试图用什么来设置标题,它都不会起作用 在接受来自前端的POST请求后,服务器端需要像这样发送响应头 server.js app.post('/register', (req, res) => { res.set({ 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' }); res.send('string'); res.end(); } r

无论我试图用什么来设置标题,它都不会起作用

在接受来自前端的
POST
请求后,服务器端需要像这样发送响应头

server.js

app.post('/register', (req, res) => {
   res.set({
       'Content-Type': 'application/json',
       'Access-Control-Allow-Origin': '*'
   });
   res.send('string');
   res.end();
}
res.set()
函数不是我尝试使用的唯一函数

我试过:

res.writeHead(201,{'Access-Control-Allow-Origin':'*')
-不起作用

res.setHeader('Access-Control-Allow-Origin','*')
-nope

res.headers()
-也不起作用

这里说的是这样的:但答案对我来说并不适用


无论我尝试了什么,服务器都不会响应启用CORS的头,我需要该头属性。我做错了什么?

尝试使用cors模块:

Access Control Expose header响应头通过列出其名称来指示哪些头可以作为响应的一部分公开

您可以在此处阅读更多信息:

res.set('Access-Control-Expose-Headers','Access-Control-Allow-Origin,…);

您在用什么测试资源?使用浏览器时,请记住,对于跨原点POST请求,浏览器将首先发送需要正确处理的飞行前请求。这是解决方案。我正试图使用越来越少的模块,因为我想编写vanilla Node.js应用程序,但Express中的标题(当涉及标题时)根本不想按我想象的方式工作。谢谢,现在一切都很好。非常感谢。
var cors = require('cors')

...

app.use(cors())
res.set('Access-Control-Expose-Headers', 'Access-Control-Allow-Origin, <any-other-custom-header>, ...');