Access-Control-Allow-Origin issues even on setting

2019-08-21 02:03发布

问题:

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();
});