非 2xx 状态代码响应是否应包含 CORS 特定标头 [英] Should non-2xx status code responses include CORS specific headers

查看:39
本文介绍了非 2xx 状态代码响应是否应包含 CORS 特定标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

非 2XX 状态代码响应是否仍应包含 CORS 特定标头,例如 Access-Control-Allow-OriginAccess-Control-Allow-Methods>访问控制最大年龄?这对客户还有意义吗?

Should non-2XX status code responses still include CORS specific headers such as Access-Control-Allow-Origin, Access-Control-Allow-Methods, and Access-Control-Max-Age? Does that even make any sense for clients?

例如:

➜  api git:(master) ✗ curl -i http://127.0.0.1:9000/dfas
HTTP/1.1 404 Not Found
Connection: close
Server: Node.js v6.3.1
Cache-Control: no-cache, no-store
Access-Control-Max-Age: 300
Access-Control-Allow-Origin: *
Content-Type: application/json
Content-Length: 60
Date: Thu, 11 Aug 2016 22:58:33 GMT

{"code":"ResourceNotFound","message":"/dfas does not exist"}

推荐答案

是的,即使使用非 2xx 响应,让服务器发送 CORS 标头也是有意义的.原因是响应中没有 CORS 标头,非 2xx 响应代码不会暴露给 JavaScript 客户端(通过 Fetch 或 XHR).响应代码可能会显示在 devtools 控制台中,但是如果没有 CORS 标头,客户端 JavaScript 将能够以编程方式确定的唯一一件事是发生了错误——但不是错误的响应代码.

Yes it makes sense to have the server send CORS headers even with non-2xx responses. The reason is that without the CORS headers in the response, the non-2xx response codes aren’t exposed to JavaScript clients (through Fetch or XHR). The response codes may show up in the devtools console but without the CORS headers the only thing the client JavaScript will be able to determine programmatically is that an error occurred—but not the response code for the error.

因此,如果您希望 JavaScript 客户端能够根据响应代码进行有用的错误处理,那么即使在非 2xx 响应中,服务器也应该发送 CORS 标头.

So if you want JavaScript clients to have the ability to do useful error handling based on the response code, the server should send CORS headers even in non-2xx responses.

这篇关于非 2xx 状态代码响应是否应包含 CORS 特定标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆