Ad

CORS POLICY EXPRESS

- 1 answer

I have this problem on my production server under express node.js :

"Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource."

But i have write that to test :

const allowCrossDomain = function(req, res, next) {


    res.header('Access-Control-Allow-Methods', 'GET, POST');
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    res.header('access-control-allow-credentials', true);

    return next();
}

app.use(allowCrossDomain)

Other example :


// CORS middleware
const allowCrossDomain = function(req, res, next) {

    var allowedOrigins = ['http://127.0.0.1:9091', 'http://localhost:9091', 'http://localhost:9090'];
    var origin = req.headers.origin;

    if(allowedOrigins.indexOf(origin) > -1){
        res.header('Access-Control-Allow-Origin', origin);
    }

    res.header('Access-Control-Allow-Methods', 'GET, POST');
    res.header('Access-Control-Allow-Headers', 'X-Requested-With,content-type,x-access-token');
    res.header('access-control-allow-credentials', true);

    return next();
}

app.use(allowCrossDomain)



// let static middleware do its job
app.use(express.static(__dirname + '/public'));


router.get('/me', function(req, res) {
  let token = req.headers['x-access-token'];
  if (!token) return res.status(401).send({ auth: false, message: 'No token provided.' });

  jwt.verify(token, config.secret, function(err, decoded) {
    if (err) return res.status(500).send({ auth: false, message: 'Failed to authenticate token.' });

    res.status(200).send(decoded);
  });
});

Ad

Answer

install cors and you wont be any problems const cors = require('cors');app.use(cors()); link on npm https://www.npmjs.com/package/cors

Ad
source: stackoverflow.com
Ad