0

The backend is written in node.js. This is the code in app.js. The chrome console reports an error. What do I need to do?

app.use(function (req, res, next) {
    if (req.method === "OPTIONS") {
        var headers = {};
        headers["Access-Control-Allow-Origin"] = "*";
        headers["Access-Control-Allow-Methods"] = "POST, GET, PUT, DELETE, OPTIONS";
        headers["Access-Control-Allow-Credentials"] = false;
        headers["Access-Control-Max-Age"] = "86400"; // 24 hours
        headers["Access-Control-Allow-Headers"] =
            "X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept";
        res.writeHead(200, headers);
        res.end();
    } else {
        res.header("Access-Control-Allow-Origin", "*");
        res.header("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE");
        res.header(
            "Access-Control-Allow-Headers",
            "Origin, X-Requested-With, Content-Type, Accept"
        );
        next();
    }
});
rain
  • 21
  • 2
  • try to use cors npm package https://www.npmjs.com/package/cors – salman Feb 24 '22 at 16:01
  • Hello, I tried it, but still getting an error, is there any other way? thank you very much。The error message is still:Refused to set unsafe header "origin" – rain Feb 25 '22 at 07:40
  • check this answer https://stackoverflow.com/questions/11182712/refused-to-set-unsafe-header-origin-when-using-xmlhttprequest-of-google-chrome – salman Feb 25 '22 at 08:45

0 Answers0