小编Cha*_*bes的帖子

Angular 13:已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头

有人可以帮助我吗?我的 CORS 政策有问题,而且我无法访问网站的后端。

operaGX 导航控制台

这是我在后端(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'

})); 

Run Code Online (Sandbox Code Playgroud)

这是前端(我使用Angular 13)导入API的代码:environment.ts

export const environment = {
  production: false,
  serverURL: 'http://localhost:3000/api/'
};

Run Code Online (Sandbox Code Playgroud)

我也尝试过这段代码,但它不起作用:

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 …
Run Code Online (Sandbox Code Playgroud)

opera swagger-node-express visual-studio-code angular

5
推荐指数
1
解决办法
5万
查看次数