Node.js服务器提供跨源请求阻止

时间:2017-01-21 21:00:41

标签: javascript node.js cors

我的Node.js服务器代码正在AWS实例上运行。它看起来像这样:

var express = require('express');
var http = require('http');
var bodyParser = require('body-parser');
var logger = require('morgan');
var cors = require('cors');
var SuperLogin = require('superlogin');
 
var app = express();
app.set('port', process.env.PORT || 3000);
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cors());
 
app.use(function(req, res, next) {
   res.header("Access-Control-Allow-Origin", "*");
   res.header('Access-Control-Allow-Methods', 'DELETE, PUT');
   res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
   next();
});
 
var config = {
  dbServer: {
    protocol: 'http://',
    host: 'localhost:5984',
    user: '',
    password: '',
    userDB: 'sl-users',
    couchAuthDB: '_users'
  },
  mailer: {
    fromEmail: 'gmail.user@gmail.com',
    options: {
      service: 'Gmail',
        auth: {
          user: 'gmail.user@gmail.com',
          pass: 'userpass'
        }
    }
  },
  security: {
    maxFailedLogins: 3,
    lockoutTime: 600,
    tokenLife: 86400,
    loginOnRegistration: true,
  },
  userDBs: {
    defaultDBs: {
      private: ['supertest']
    }
  },
  providers: { 
    local: true
  }
}
 
// Initialize SuperLogin 
var superlogin = new SuperLogin(config);
 
// Mount SuperLogin's routes to our app 
app.use('/auth', superlogin.router);
 
app.listen(app.get('port'));
console.log("App listening on " + app.get('port'));

我正在使用离子2应用程序,它使PUT调用运行在端口3000上的Node.js服务器。在我的笔记本电脑上的浏览器中运行应用程序时(使用ionic serve),PUT调用给出了CORS错误:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading 
the remote resource at http://ec2-xx-xxx-xx-4xx.eu-central-1.compute.amazonaws.com/auth/login. 
(Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

据我所知,服务器代码设置为允许所有来源,但我仍然收到此错误。

1 个答案:

答案 0 :(得分:3)

这是因为预检被触发,这意味着OPTIONS请求将到达您的服务器。这在很好地解释了 {@ 3}}正如@johannes merz在你的问题评论中指出的那样。

您可以通过以下方式指示您的服务器接受它:

app.use(function(req, res, next) {
   res.header("Access-Control-Allow-Origin", "*");
   res.header('Access-Control-Allow-Methods', 'DELETE, PUT');
   res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
   if ('OPTIONS' == req.method) {
      res.sendStatus(200);
    }
    else {
      next();
    }});