node.js - 我还需要使用 CORS 吗?
问题描述
我正在开发 Web 应用程序的后端,我已经为任何路线设置了全局标头,如下所示
Router.js 文件
Router.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header(
"Access-Control-Allow-Headers",
"Origin, Accept, Accept-Version,Set-Cookie, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version, X-Response-Time, X-PINGOTHER, X-CSRF-Token,Authorization"
);
res.header("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS");
res.header("Content-Type", "application/json");
res.header("Access-Control-Allow-Credentials", true);
next();
});
服务器.js
//user defined middlewares
app.use("/",Router);
我是否需要再次设置 cors,因为我已经允许从任何来源访问?,我也允许飞行前请求
解决方案
/
只有在请求服务的根目录时才会发送这些标头。对于任何其他端点,例如/getsomething
不会设置 CORS 标头。
如果您的服务器的用例只是 root 访问 - 或者您需要仅为 root 访问设置 CORS 标头,那么 NO - 您无需执行任何操作。
但是,如果您有更多路由并且还需要它们与 CORS 兼容,那么您将不得不在所有路由之上使用通用中间件。
另一点是您的 CORS 中间件不应为OPTIONS
预检请求发送任何其他内容。因此,最好在此处结束对OPTIONS
请求的响应。
这是组合代码:
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header(
"Access-Control-Allow-Headers",
"Origin, Accept, Accept-Version,Set-Cookie, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version, X-Response-Time, X-PINGOTHER, X-CSRF-Token,Authorization"
);
res.header("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS");
res.header("Content-Type", "application/json");
res.header("Access-Control-Allow-Credentials", true);
if (req.method === 'OPTIONS')
res.status(200).send();
else
next();
});
推荐阅读
- python - 是否可以使用 Cerberus 验证 yaml 文件的键名和字典名称?
- ruby - 需要一些帮助遍历数组并进行有条件的更改
- java - 如何在android中制作回调链
- python - 尝试使用 Image.save() 保存图像时出错
- sql - SQL:如何只选择最旧的记录
- java - Eclipse 的 Content Assist 不适用于 java.util.Comparator
- javascript - 附加条不会在 svg 元素上绘制
- java - 不兼容的类型:View 无法转换为 LinearLayout
- perl - 在 perl 中立即调用函数表达式 (IIFE) 的最佳方法?
- ios - iOS AutoFill 功能:有没有办法拦截 AutoFill 事件?