从本地主机启动服务器时,没有出现任何错误。但是部署到Heroku之后,它在某些特定路线上给了我以下cors错误:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:8080' is therefore not allowed access. The response had HTTP status code 503. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
我已经尝试了几乎所有方法来解决此错误,并且还尝试了在堆栈溢出时发现的所有可能解决方案,但是没有任何效果。
我的代码很简单:有一个登录功能可以向API端点发送请求,并且该端点可以确保管理员是否已通过身份验证。
我的服务器代码:(使用express js)
const expressApp = require('express');
const port = process.env.PORT || 3000;
const cors = require('cors');
const express = expressApp();
const bodyParser = require('body-parser');
const session = require('express-session');
const adminRoutes = require('./admin/admin-routes');
const userRoutes = require('./users/user-routes');
const bookingRoutes = require('./booking/booking-routes');
const contactRoutes = require('./contact-us/contact-routes');
require('./dbConnection.js');
express.use(function (req, res, next) {
console.log(req.headers);
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header("Access-Control-Allow-Methods", "POST,DELETE,PUT,GET,OPTIONS");
res.header("Access-Control-Allow-Headers", req.headers['access-control-request-headers']);
res.header("Access-Control-Request-Method", req.headers['access-control-request-method']);
next();
});
客户端是:
fetch(url, {
method: "POST",
password: this.password,
body: JSON.stringify({
bodyData: { email }
}),
headers: {
'Access-Control-Allow-Origin': '*',
"Content-Type": "application/json"
}
}).then(res => {
return res.json()
}).then(user => {
// somthing here
}).catch(error => {
console.log(error);
})