【问题标题】:Why am I getting CORS origin although I defined cors "Access-Control-Allow-Origin" and set it with the value " * "尽管我定义了 cors“Access-Control-Allow-Origin”并将其设置为值“*”,但为什么我得到了 CORS 来源
【发布时间】:2021-11-18 10:58:17
【问题描述】:

我正在创建一个 MEAN 应用。我已经在 netlify 上部署了前端,在 heroku 上部署了后端。

在本地,所有路线都可以正常工作。

但在生产模式下我收到此错误:

从源“https://myfrontendlink.netlify.app”访问“https://mybackendLink.herokuapp.com/api/upload-image-pub/614f30ce01777500042b0238”的 XMLHttpRequest 已被 CORS 策略阻止:否请求的资源上存在 Access-Control-Allow-Origin' 标头。

在我的 app.js 文件中,我有这个 CORS 配置:

app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Authorization, X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Allow-Request-Method');
    res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, DELETE');

    next();
});

提前感谢您的帮助

【问题讨论】:

    标签: node.js cors


    【解决方案1】:

    你可以使用cors来避免Access-Control-Allow-Origin的错误,

    const cors = requires('cors');
    // ..... Other Code
    app.use(cors());
    

    通过在您的应用程序广告中使用 cors 中间件,您可以解决Access-Control-Allow-Origin 的问题

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-25
      • 1970-01-01
      • 2017-07-15
      • 2019-11-20
      • 2022-11-11
      • 2019-10-02
      • 1970-01-01
      • 2017-05-16
      相关资源
      最近更新 更多