使用axios发送请求时如何添加X-XSRF-TOKEN头部

6
如果我在服务器端设置了XSRF-TOKEN cookie,是否需要设置任何内容来发送X-XSRF-TOKEN头? 根据https://github.com/axios/axios/blob/master/lib/defaults.js#L74https://github.com/axios/axios/blob/master/dist/axios.js#L1072,好像不需要设置,但我没有看到头部发送出去。同时我已将withCredentials设置为true,因此我符合OR中的第一个检查条件。
var xsrfValue = (config.withCredentials || isURLSameOrigin(config.url)) && config.xsrfCookieName ?
            cookies.read(config.xsrfCookieName) :
            undefined;

          if (xsrfValue) {
            requestHeaders[config.xsrfHeaderName] = xsrfValue;
}

因此,如果config.xsrfCookieName是默认值.....

更新:

所以,我的OPTIONS预检请求的CORS已经可以使用,现在也可以使用POST请求,但是没有发送X-XSRF-TOKEN

  methods: {
    onSubmit(e) {
      this.axios
        .post(
          e.target.action,
          { data: this.form },
          {
            withCredentials: true,
            xsrfCookieName: "XSRF-TOKEN",
            xsrfHeaderName: "X-XSRF-TOKEN"
          }
        )
        .then(res => {
          console.log(res)
        })
        .catch(err => {
          this.errors.push(err)
        })
    }
  }

感谢您的选择。
谢谢。

有什么想法吗?https://github.com/axios/axios/issues/1838 - Gavin Henry
1个回答

4
我遇到了同样的问题,关注了请求的cookies选项卡上的cookie的“secure”标志,但在“应用程序”选项卡下的cookies中没有显示:

XSRF-TOKEN secure

在我的情况下,我不得不请求后端将其设置为关闭状态。这是因为,作为安全措施,您无法通过javascript访问它。
document.cookie // is empty

7
“安全”cookie可以被JavaScript读取,但无法读取“Http-only”cookie。有此属性的cookie仍然可以在访问客户端硬盘或未设置HttpOnly cookie属性的情况下通过JavaScript进行读取/修改。https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#Secure - npretto

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接