且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

CORS 错误:预检响应中的 Access-Control-Allow-Headers 不允许请求标头字段授权

更新时间:2022-05-20 22:37:56

您还必须在允许的标题中添加选项.浏览器在发送原始请求之前发送预检请求.见下文

You have to add options also in allowed headers. browser sends a preflight request before original request is sent. See below

 res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,PATCH,OPTIONS');

来自https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/OPTIONS

在 CORS 中,发送带有 OPTIONS 方法的预检请求,以便服务器可以响应是否可以使用这些参数发送请求.Access-Control-Request-Method 标头作为预检请求的一部分通知服务器,当实际请求发送时,它将使用 POST 请求方法发送.Access-Control-Request-Headers 标头通知服务器,当实际请求被发送时,它将与 X-PINGOTHERContent-Type 一起发送 自定义标题.在这些情况下,服务器现在有机会确定它是否希望接受请求.

In CORS, a preflight request with the OPTIONS method is sent, so that the server can respond whether it is acceptable to send the request with these parameters. The Access-Control-Request-Method header notifies the server as part of a preflight request that when the actual request is sent, it will be sent with a POST request method. The Access-Control-Request-Headers header notifies the server that when the actual request is sent, it will be sent with a X-PINGOTHER and Content-Type custom headers. The server now has an opportunity to determine whether it wishes to accept a request under these circumstances.

已编辑

您可以通过使用 npmjs.com/package/cors npm 包来避免这种手动配置.我有也用过这个方法,简单明了.

You can avoid this manual configuration by using npmjs.com/package/cors npm package.I have used this method also, it is clear and easy.