javascript Http requests withCredentials 这是什么,为什么要使用它?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27406994/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 07:27:21  来源:igfitidea点击:

Http requests withCredentials what is this and why using it?

javascriptangularjshttp

提问by rluta

I had a problem with CORS with node and angular and adding this option with true solved my problem. But I don't find info about what it is and what it is doing. Please can someone explain?

我在使用节点和角度的 CORS 时遇到了问题,并将此选项添加为 true 解决了我的问题。但我没有找到关于它是什么以及它在做什么的信息。请问有人可以解释一下吗?

回答by rluta

Short answer:

简答:

withCredentials()makes your browser include cookies and authentication headers in your XHR request. If your service depends on any cookie (including session cookies), it will only work with this option set.

withCredentials()使您的浏览器在您的 XHR 请求中包含 cookie 和身份验证标头。如果您的服务依赖于任何 cookie(包括会话 cookie),则它仅适用于此选项集。

Longer explanation:

更长的解释:

When you issue an Ajax request to a different origin server, the browser may send an OPTIONS pre-flight request to the server to discover the CORS policy of the endpoint (for non-GET requests).

当您向不同的源服务器发出 Ajax 请求时,浏览器可能会向服务器发送 OPTIONS 预检请求以发现端点的 CORS 策略(对于非 GET 请求)。

Since the request may have been triggered by a malicious script, to avoid automatically leaking authentication information to the remote server, the browser applies the following rules :

由于请求可能是由恶意脚本触发的,为了避免自动将认证信息泄露给远程服务器,浏览器应用以下规则:

For GET requests, include cookie and authentication information in the server request :

对于 GET 请求,在服务器请求中包含 cookie 和身份验证信息:

  • if XHR client is invoked with the withCredentialsoption is set to true
  • and if the server reply does not include the CORS Header Access-Control-Allow-Credentials: true, discard response before returning the object to Javascript
  • 如果在withCredentials选项设置为 true 的情况下调用 XHR 客户端
  • 如果服务器回复不包含 CORS Header Access-Control-Allow-Credentials: true,则在将对象返回给 Javascript 之前丢弃响应

For non GET requests, include cookie and authentication information only:

对于非 GET 请求,仅包含 cookie 和身份验证信息:

  • if withCredentialsis set to true on the XHR object
  • and the server has included the CORS Header Access-Control-Allow-Credentials: true in the pre-flight OPTIONS
  • 如果withCredentials在 XHR 对象上设置为 true
  • 并且服务器在飞行前选项中包含了 CORS Header Access-Control-Allow-Credentials: true

回答by Akshay Vijay Jain

Short answer from Axios documentation

withCredentialsindicates whether or not cross-site Access-Control requests should be made using credentials

Axios 文档中的简短回答

withCredentials表明是否应使用凭据进行跨站点访问控制请求

Credentials are cookies, authorization headers or TLS client certificates Reference

凭据是 cookie、授权标头或 TLS 客户端证书参考

Default value of withCredentialsis false

的默认值withCredentials就是false