我发现了cors错误。我有什么遗漏吗?下面是我的代码和我得到的错误。
应用程序信息
:
后端使用创建api网关的无服务器npm===上载到lambda上。
Mongodb托管在aws-ec2实例上。
前端/React托管在s3 bucket上。
非常感谢!
Access to fetch at '[node.js api-url, which is hosted on api-gateway/lambda]' from origin '[front-end react-url, which is hosted on aws-s3 bucket]' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Credentials' header in the response is 'false' which must be 'true' when the request's credentials mode is 'include'.
Node.js代码:
db.initialize();
initAxios(defaults);
const app = express();
if (process.env.ENV === 'production') {
app.server = https.createServer(config.sslOptions, app);
} else {
app.server = http.createServer(app);
}
app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true,
}));
app.use(expressSession({
secret: process.env.JWT_SECRET_KEY,
resave: true,
saveUninitialized: true,
}));
app.use(passport.initialize());
app.use(passport.session());
var corsOptions = {
origin: function (origin, callback) {
callback(null, true)
},
credentials: true
}
app.use(cors(corsOptions));
// I added the below part so maybe it would work but it didn't :)
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
// I added the above part so maybe it would work but it didn't :)
app.use(morgan('combined', {
stream: logger.stream
}));
app.use(`/api/v${process.env.API_VERSION}`, router);
前端反应代码:
export async function login(data) {
return fetch(`[api-url]auth/login`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
credentials: 'include',
// credentials: 'same-origin',
body: JSON.stringify({
username: data.username,
password: data.password,
}),
})
.then((response) => {
return response.json()
})
.then(onSuccess)
.catch(onFail)
}
在这之前:
app.use(cors({
credentials: true,
origin: true,
}));
所以我转换成:
app.use(cors(corsOptions));
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
谢谢您!