【问题标题】:How to add cookie in cross domain xhr call from client?如何在来自客户端的跨域 xhr 调用中添加 cookie?
【发布时间】:2018-01-25 10:01:17
【问题描述】:

例如,如果我有一个来自域 A 的 cookie,并且我的 javascript 客户端代码位于域 B 中。当我从域B 向域A 发出ajax 请求时,浏览器是否会自动将域A 的cookie 传递给请求?

我应该添加一个设置来设置 cookie 吗?我的 javascript 客户端似乎无法访问域 A cookie。

作为参考,我正在使用这个库https://github.com/naugtur/xhr

【问题讨论】:

    标签: javascript cookies


    【解决方案1】:

    使用withCredentials:true

    这允许来自远程域的 cookie 来回传递,前提是在远程端点设置了正确的访问控制标头以允许 "withCredentials"

    参考:XMLHttpRequest.withCredentials

    【讨论】:

      【解决方案2】:

      您正在寻找 XHR 库的 withCredentials 设置。

      所以:

      var xhr = require("xhr")
      
      xhr({
          withCredentials: true, // <--- this!
          method: "post",
          body: someJSONString,
          uri: "/foo",
          headers: {
              "Content-Type": "application/json"
          }
      }, function (err, resp, body) {
          // check resp.statusCode
      })
      

      【讨论】:

        猜你喜欢
        • 2012-08-31
        • 2010-12-28
        • 1970-01-01
        • 2019-07-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-02-10
        • 1970-01-01
        相关资源
        最近更新 更多