【问题标题】:No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://myappurl.com is therefore not allowed access请求的资源上不存在“Access-Control-Allow-Origin”标头。 Origin 'https://myappurl.com 因此不允许访问
【发布时间】:2018-10-15 04:39:34
【问题描述】:

我正在编写一个 vue 应用程序并使用 Node.js Api。我已经在后端包含了 cors,其他 post 方法效果很好。但是在这条路由中有一个 Nginx 502 Bad Gateway。

chrome控制台报错

Failed to load resource: the server responded with a status of 502 (Bad Gateway)

Failed to load : No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin is therefore not allowed access. The response had HTTP status code 502.

app.js CORS

app.use(function(req, res, next) {
  res.setHeader("Access-Control-Allow-Origin","*");
  res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept,Authorization");
    res.setHeader('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,PATCH,OPTIONS');
    res.setHeader("Access-Control-Allow-Credentials", "false")

  next();
});

我的 AddPatient 组件和我的 Axios 在 pastebin 上可用

【问题讨论】:

    标签: javascript node.js vue.js axios


    【解决方案1】:

    setHeader 你只写 一个 标题,覆盖前一个。您必须使用res.header(),它允许您编写多个标题。你可以这样做:

    app.use(function(req, res, next) {
      res.header("Access-Control-Allow-Origin","*");
      res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept,Authorization");
      res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,PATCH,OPTIONS');
      res.header("Access-Control-Allow-Credentials", "false")
    
      next();
    });
    

    【讨论】:

    • 此外,Access-Control-Allow-Credentials 的 only 允许值为 true。要么不通过,要么将其作为 true 传递。
    • 这不是真的,你可以为header指定一个URL之类的值
    猜你喜欢
    • 2013-12-24
    • 2017-02-04
    • 2014-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-09
    • 2014-03-13
    相关资源
    最近更新 更多