科尔斯"It does not have HTTP ok status."



NodeJS Express platform.现在使用 Zeit 2。不能使用服务器.js作为从后端发送的代理来防止 CORS。所以,也没有与CORS问题搏斗。测试桌面:chrome,safari,Firefox。手机:铬,火狐。已经测试过使用 HTTPS 在 Now 上托管,与我在localhost:3000127.0.0.1:3000上本地得到的错误相同,使用端口80相同。

Access to fetch at 'https://**MY_URL**/user/login' from origin 'http://127.0.0.1:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

我使用 https://www.npmjs.com/package/cors 来设置我的 CORS 配置:

app.use(cors({
'allowedHeaders': ['Content-Type', 'API-Key', 'API-Secret', 'Access-Control-Allow-Headers'', 'accept', 'client-security-token'],
'exposedHeaders': ['sessionId'],
'origin': '*',
'methods': 'GET, HEAD, PUT, PATCH, POST, DELETE, OPTIONS',
'preflightContinue': false,
'credentials': true
}));

CORS 设置似乎不适合我,所以我尝试使用now.json文件,如下所示(修剪后的 veersion):

{
"name": "my-test-api",
"version": 2,
"routes": [
{
"src": "/.*",
"methods": ["GET", "POST", "OPTIONS"],
"headers": { "Access-Control-Max-Age": "1000", "Access-Control-Allow-Methods": "GET, HEAD, PUT, PATCH, POST, DELETE, OPTIONS", "Access-Control-Allow-Origin": "*", "Accept": "text/plain", "Content-Type": "text/plain", "Access-Control-Allow-Headers": "sessionId, Content-Type, API-Key, API-Secret, Access-Control-Allow-Headers", "Access-Control-Expose-Headers": "sessionId", "Access-Control-Allow-Credentials": "true" },
"continue": true
},
{ "src": "/user/login", "methods": ["POST"], "dest": "index.js" }
]
}

甚至在我的所有回复中添加了状态代码 200,但没有任何成功。删除 Npm-cors-package 不会改变任何东西,但删除 Now.json 会完全破坏东西,即使我在app.use(cors())中指定了它,我也从 MDN 收到此错误。

不知道该怎么办,一直在为此苦苦挣扎。cURL 或其他可以使用后端代理的主机没有问题。

您可能需要为航线启用飞行前请求

app.use(cors())
app.options('/post/login', cors()) // enable pre-flight requests
app.post('/post/login', (req, res, next) => {
// your code here
});

或适用于所有路线

app.options('*', cors())

您可以设置预检响应的 HTTP 状态。

app.options('*', function (req,res) { res.sendStatus(200); });

当预检(选项)请求返回 404 时,我遇到了这个神秘的错误。我最终发现我使用了不正确的路径,我的路由器(Golang httprouter)404s OPTIONS用于不存在的路由。

您可以使用nginx的反向代理将80端口的请求代理到3000端口,它将正常工作

请尝试添加一行并从 express 和 now.json 中删除旧的 cors 配置

app.use(cors());

就是这样。CORS 现已启用。 如果向应用发出请求,则会注意到返回的新标头:Access-Control-Allow-Origin: *

我使用Nginx进行cors配置。但是对于 docker 中的本地开发,最好使用快速中间件:

const corsMiddleware = (req, res, next) => {
res.header('Access-Control-Allow-Origin', '*')
.header('Access-Control-Allow-Headers', 'Authorization,Accept,Origin,DNT,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range')
.header('Access-Control-Allow-Methods', 'GET,POST,OPTIONS,PUT,DELETE,PATCH');
if (req.method === 'OPTIONS') {
res.sendStatus(200);
} else {
next();
}
}
app.use(corsMiddleware);

https://cors-anywhere.herokuapp.com/yoururl

例:

axios.get('https://cors-anywhere.herokuapp.com/spo.handball4all.de/Spielbetrieb/index.php?orgGrpID=56&score=45991')
.then(response => {
const $ = cheerio.load(response.data);
})

相关内容

最新更新