【发布时间】:2022-07-19 04:06:25
【问题描述】:
谁能帮帮我,我的 CORS 政策有问题,我无法访问网站的后端。
这是我在后端(node.js)中使用的代码:
app.use(cors({
Access_Control_Allow_Origin: "*",
origin:"*",
methode:['GET','POST','PATCH','DELETE','PUT'],
allowedHeaders:'Content-Type, Authorization, Origin, X-Requested-With, Accept'
}));
这是前端(我使用 Angular 13)导入 API 的代码: 环境.ts
export const environment = {
production: false,
serverURL: 'http://localhost:3000/api/'
};
我也试过这段代码,但没有用:
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:4200');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
next();
});
【问题讨论】:
-
我会再次检查docs。
Access_Control_Allow_Origin是......但不是 cors 包的一部分,methode拼写错误,您有http://localhost:8888作为允许来源,但 Angular 在 4200 上运行,等等。从文档开始并慢慢添加。跨度> -
愿意打赌是因为
methode -
我从其他成员的响应中复制了此代码,并且我已将代码的来源更改为 4200,但它不起作用
-
试试第二个答案。这解决了我的问题。参考这个stackoverflow.com/questions/57009371/…
标签: angular visual-studio-code opera swagger-node-express