首页 > 解决方案 > 使用 axios 和 nuxt 发出 GET 请求时如何获取响应标头?

问题描述

我正在尝试从我的后端获取 CSRF 令牌。使用时fetch我可以简单地去

                const response = await fetch(`/account/csrf/`, {
                    credentials: "include",
                });
                
                const data = await response
                let csrfToken = data.headers.get("X-CSRFToken"); // how is this done with axios?

我试过了

const csrfToken = await this.$axios.$get(`/account/csrf/`, {
 /*
 what is the equivalent here? 
 I don't wish to *send* anything to the server, but rather retrieve, so I guess I can't use headers {}
 */
});

标签: axiosnuxt.js

解决方案


$get()您可以使用 Axios 中的 raw 方法,而不是从 nuxt 模块中获取帮助程序,get()如下所示:

const { data, headers } = await this.$axios.get('/account/csrf/', {
  withCredentials: true
});

const csrfToken = headers["X-CSRFToken"];

推荐阅读