Access-Control-Allow-Origin issues even on setting it up

牧云@^-^@ 提交于 2019-12-13 20:17:18

问题


My nodejs/express includes:

app.use(function handleAppError(err, req, res, next) {
    const msg = 'ERROR: App error: ' + util.inspect(err);
     // Website you wish to allow to connect
    res.setHeader('Access-Control-Allow-Origin', '*');

    console.log(msg);
    if (res.headersSent) {
        next(err);
    } else {
        res.status(500).send(msg);
    }
});

…but on making a call, I still end up with an error in Chrome:

XMLHttpRequest cannot load http://:8080/management-api/v1/bots. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access.


回答1:


You need to handle the OPTIONS method. Try this

app.all("/*", function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Cache-Control, Pragma, Origin, Authorization, Content-Type, X-Requested-With");
    res.header("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE");
    if (req.method === "OPTIONS")
        res.send(200);
    else
        next();
});


来源:https://stackoverflow.com/questions/45851771/access-control-allow-origin-issues-even-on-setting-it-up

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!