夜间模式CodeSnippetStyle:
日间模式CodeSnippetStyle:

0%


[跨域问题]:Response to preflight request doesn't pass access control check: It does not have HTTP ok status. 的解决

先将注意力放在报错信息上:
“Response to preflight request doesn't pass access control check: It does not have HTTP ok status.”

首先什么是 preflight request ?

A CORS preflight request is a CORS request that checks to see if the CORS protocol is understood and a server is aware using specific methods and headers.
** It is an OPTIONS request**, using three HTTP request headers: Access-Control-Request-Method, Access-Control-Request-Headers, and the Origin header.
@https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request

也就是在一个HTTP 请求之前,会先发送一个 METHOD 为 OPTION 的预请求,去询问服务器是否支持跨域请求。

问题的解决

首先设定一个响应拦截器:

var app = express();

app.use((req, res, next) => {
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Headers', '*');
  next();
});

然后设定一个 OPTION 的handler, 所匹配的 path 就是你先前发送请求失败的 path:

app.options('/example', (req, res) => {
  res.status(200).send();
});

其他的解决办法

解决办法主要因场景而定,说说我这个问题怎么遇到的:
我这里是在写一个 graphql 的客户端请求处理的 demo,
所以我需要模拟客户端请求, 是一个最简单的 cs 场景。
我提供了一个 html 文件,其中用 fetch 向node express 端的 graphql handler 发送请求。
我的启动方式,我尝试了直接本地浏览器通过 file协议打开 index.html, 这明显是会跨域的。 也尝试了用 live-server vscode 插件将该 index.html serve 在了 5500 默认端口。 这明显也是会跨域的。
所以我先 设定了 res.setHeader('Access-Control-Allow-Origin', '*');
发现还是不行。 google 一番然后就有了这篇笔记。

对于测试开发来讲,其实还可以直接让 express 去 serve index.html, 这样就不存在跨域的问题了
目录结构:

.
├── app.js
└── test
    └── index.html
app.use(express.static("test"))
posted @ 2022-11-23 08:16  暮冬有八  阅读(8724)  评论(0编辑  收藏  举报
BACK TO TOP

😀迷海无灯听船行。Github WeChat