且构网

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

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-PINGOTHER发送 Content-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 package。我也使用过这种方法,很简单明了。

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.