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

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

问题描述

非2XX状态代码响应仍应包含CORS特定的标头,例如 Access-Control-Allow-Origin Access-Control-Allow-Methods Access-Control-Max-Age ?这样对客户来说还有意义吗?

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天全站免登陆