【发布时间】:2016-08-27 19:03:43
【问题描述】:
我正在一个框架中实现 CORS(跨域资源共享)。
我知道,当使用 Jquery 的 ajax(...) 发出 XMLHttpRequest 请求并且 withCredentials 属性为 true 时,服务器必须响应这两件事:
Access-Control-Allow-Credentials: trueAccess-Control-Allow-Origin:[THE_DOMAIN]
服务器不能使用通配符响应Access-Control-Allow-Origin:*:doesn't work!
我的问题:我怎么知道在服务器上withCredentials: true 已被使用,所以我不使用通配符?
我比较了使用withCredentials: false 和withCredentials: true 时发送的标头,它们是相同的!
所以,如果我确实想在客户端请求时允许凭据,这是否意味着我不能,永远,使用Access-Control-Allow-Origin:*?
【问题讨论】:
-
如果
withCredentials设置为 true,您还应该收到在源域上设置的任何 cookie,我不确定这对于初始请求是否为 true,或者仅在服务器响应之后Access-Control-Allow-Credentials: true(我可以想象这两种情况都是正确的,尽管我认为后者是最合理的)。至于通配符,我倾向于始终指定允许的域(来自原始标头)。 this answer might help. -
@RogierSpieker 当使用
withCredentials: true进行查询但没有任何cookie 时,使用通配符也会失败。我不认为在客户端使用withCredentials: true时强制客户端发送cookie 是可取的……你不知道他的代码逻辑。所以你不能真的依赖cookie的存在,我认为。感谢您的帮助! -
我并不是在暗示应该强制设置 cookie,只是如果设置了
withCredentials: true就会发生这种情况。在这种情况下,cookie 的存在将表明withCredentials为true。
标签: javascript jquery ajax cors