被CORS策略阻止:不存在“ Access-Control-Allow-Origin”标头[Nodejs]

时间:2019-03-18 20:37:26

标签: node.js express cors xmlhttprequest

确切的错误消息:Access to XMLHttpRequest at 'http://localhost:7000/profile/picture?url=me' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

我使用的是Express版本4.16.4。在我的应用程序中,上传图像并注销后,当我重新登录时出现此错误。我在主服务器中添加了以下内容:

app.use('*', cors({ 
        credentials: true, 
        origin: true, 
        methods: 'GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS', 
        preflightContinue: true
    }));

... (routes here)

app.all('*', function (req, res, next) {
        origin = req.get('origin');

        // Development whitelist
        var whitelist = ['http://localhost:8080', 'http://localhost:8081'];

        corsOptions = {
            origin: function (origin, callback) {
                    var originIsWhitelisted = whitelist.indexOf(origin) !== -1;
                    callback(null, originIsWhitelisted);
            }
        };

        next();
    });

我得到了OPTIONS条日志,但是没有找到任何路由。同样,Node中也不会抛出任何错误消息。

1 个答案:

答案 0 :(得分:-2)

尝试这种方式:

const whitelist = [
  'http://localhost:8080',
  'http://localhost:8081'
];

const corsOptions =  (origin) => {
    return whitelist.some(wl=> wl.localeCompare(origin) === 0);
};

app.use( (req, res, next) => {
    res.setHeader('Access-Control-Allow-Credentials', true);
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept');
    if(!corsOptions(req.headers.origin)){
      const error = {
        erro : "This aren't a public API."
      };
      res.sendStatus(500).json(error);
      next();
    }
    if ('OPTIONS' == req.method) {
      res.sendStatus(200);
    } else {
      next();
    }
  });