gpt4 book ai didi

javascript - Node.js 服务器阻止跨源请求

转载 作者:行者123 更新时间:2023-12-03 19:43:30 25 4
gpt4 key购买 nike

我的 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'));

我正在使用一个 ionic 2 应用程序,它对在端口 3000 上运行的 Node.js 服务器进行 PUT 调用。当在我的笔记本电脑上的浏览器中运行该应用程序时(使用 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).

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

最佳答案

这是因为预检被触发,这意味着一个 OPTIONS 请求将到达您的服务器。这在 this description by MDN正如@johannes merz 在对您的问题的评论中指出的那样。

您可以指示您的服务器通过 rep 接受它,如下所示:

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

关于javascript - Node.js 服务器阻止跨源请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41784454/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com