spine, node.js (express) and Access-Control-Allow-Origin

岁酱吖の 提交于 2019-12-03 11:43:53

app.get will only respond to GET requests. If the browser is preflighting it with an OPTIONS request, express will send an error because it doesn't have any listeners for those requests. Try adding this code in addition to yours and see if it works:

app.options('/posts', function(req, res){
  console.log("writing headers only");
  res.header("Access-Control-Allow-Origin", "*");
  res.end('');
});

Also note: if you're sending cookies with the request (withcredentials=true), then the Access-Control-Allow-Origin header cannot be *, it must be the exact value in the Origin header that the browser automatically adds to the ajax request like so:

res.header("Access-Control-Allow-Origin", req.headers.origin);

This is for security reasons - if you're doing something that requires cookies, then it is more likely that you will want to actually check that the origin is an allowed website in order to avoid CSRF attacks.

This middleware will allow CORS using Express, the key is detecting the preflight request OPTIONS and returning a response to avoid 404's or duplicate database queries. See resource: http://cuppster.com/2012/04/10/cors-middleware-for-node-js-and-express/

var methodOverride = require('method-override');
app.use(methodOverride());

// ## CORS middleware
// see: http://stackoverflow.com/questions/7067966/how-to-allow-cors-in-express-nodejs
var allowCrossDomain = function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');

    // intercept OPTIONS method
    if ('OPTIONS' == req.method) {
      res.send(200);
    }
    else {
      next();
    }
};
app.use(allowCrossDomain);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!