前后端分离的协作开发方式,已经被很多公司采用。若前后端部署在不同的域名下,就会碰到跨域的问题。对于跨域的问题,W3C 有标准的解决方案,即跨域资源共享(Cross-origin resource sharing),缩写为 CORS。详细了解 CORS,可以参考阮一峰的博文:跨域资源共享 CORS 详解。下面介绍一下与跨域相关的 HTTP 响应头部字段:Access-Control-Allow-Origin 。
先看 W3C 对其的说明如下:
The Access-Control-Allow-Origin header indicates whether a resource can be shared based by returning the value of the Origin request header, "*", or "null" in the response. ABNF:
Access-Control-Allow-Origin = "Access-Control-Allow-Origin" ":" origin-list-or-null | "*"In practice the origin-list-or-null production is more constrained. Rather than allowing a space-separated list of origins, it is either a single origin or the string "null".
上述说明的大致意思:Access-Control-Allow-Origin 的值是请求头 Origin 字段的值、"*"、"null",然后是 ABNF 格式的定义,最后提示,在产品实际中 origin-list-or-null 多用来做限制,它不是一