我需要将CORS设置为在由express提供的脚本上启用。我如何设置这些公共/资产返回的响应头?
当前回答
npm中至少有一个中间件可以在Express中处理CORS: CORS。[见@mscdex answer]
这是如何设置自定义响应头,从ExpressJS DOC
res.set(field, [value])
将报头字段设置为value
res.set('Content-Type', 'text/plain');
或者传递一个对象一次设置多个字段。
res.set({
'Content-Type': 'text/plain',
'Content-Length': '123',
'ETag': '12345'
})
混叠
res.header(field, [value])
其他回答
npm中至少有一个中间件可以在Express中处理CORS: CORS。[见@mscdex answer]
这是如何设置自定义响应头,从ExpressJS DOC
res.set(field, [value])
将报头字段设置为value
res.set('Content-Type', 'text/plain');
或者传递一个对象一次设置多个字段。
res.set({
'Content-Type': 'text/plain',
'Content-Length': '123',
'ETag': '12345'
})
混叠
res.header(field, [value])
npm中至少有一个中间件可以在Express中处理CORS: CORS。
首先在响应头中添加“field”
response.set('field', 'value');
然后你要做的就是暴露你的头文件
response.set('Access-Control-Expose-Headers', 'field')
你也可以添加一个中间件来添加CORS头,像这样就可以了:
/**
* Adds CORS headers to the response
*
* {@link https://en.wikipedia.org/wiki/Cross-origin_resource_sharing}
* {@link http://expressjs.com/en/4x/api.html#res.set}
* @param {object} request the Request object
* @param {object} response the Response object
* @param {function} next function to continue execution
* @returns {void}
* @example
* <code>
* const express = require('express');
* const corsHeaders = require('./middleware/cors-headers');
*
* const app = express();
* app.use(corsHeaders);
* </code>
*/
module.exports = (request, response, next) => {
// http://expressjs.com/en/4x/api.html#res.set
response.set({
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'DELETE,GET,PATCH,POST,PUT',
'Access-Control-Allow-Headers': 'Content-Type,Authorization'
});
// intercept OPTIONS method
if(request.method === 'OPTIONS') {
response.send(200);
} else {
next();
}
};
@klode的答案是正确的。
但是,您应该设置另一个响应标头以使其他人可以访问您的标头。
例子:
首先,在响应头中添加“page-size”
response.set('page-size', 20);
然后,你所需要做的就是暴露你的头文件
response.set('Access-Control-Expose-Headers', 'page-size')
推荐文章
- 一元加/数字(x)和parseFloat(x)之间的区别是什么?
- angularjs中的compile函数和link函数有什么区别
- 删除绑定中添加的事件监听器
- 很好的初学者教程socket.io?
- HtmlSpecialChars在JavaScript中等价于什么?
- React: 'Redirect'没有从' React -router-dom'中导出
- 如何在React中使用钩子强制组件重新渲染?
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 我如何等待一个承诺完成之前返回一个函数的变量?
- CALL_AND_RETRY_LAST分配失败-进程内存不足
- 在JavaScript中根据键值查找和删除数组中的对象
- 使嵌套JavaScript对象平放/不平放的最快方法
- 在Ubuntu上安装Node.js
- 如何以及为什么'a'['toUpperCase']()在JavaScript工作?
- 有Grunt生成index.html不同的设置