VUE 中的 Axios 承诺失败,无法读取未定义的 属性 'toUpperCase'

Axios promise in VUE failed with Cannot read property 'toUpperCase' of undefined

在我用 VUE 制作的 SPA 中,我正在设置我的 Axios 存储库(或 Api 文件),但我在使用拦截器时遇到了问题。

基本上,如果 jwtoken 已过期或缺少拦截器,我在调试中看到 401 错误,我在网络调试中看到对 api 服务器的尝试。

问题出在我获得有效的 jwtoken 时。在这种情况下,我没有尝试网络 window 和错误:

TypeError: Cannot read property 'toUpperCase' of undefined
at dispatchXhrRequest (app.js:57825)
at new Promise (<anonymous>)
at xhrAdapter (app.js:57808)
at dispatchRequest (app.js:58416)

这应该意味着承诺错误,也可能是配置错误,但我需要新的眼光来修复...

这是有承诺的请求代码:

const headers = {
    'X-CSRF-TOKEN': csrfToken,
    'X-Requested-With': 'XMLHttpRequest',
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${token}`,
};

client.interceptors.request.use(
    config => {
        if (!token) {
            return config;
        }

        const newConfig = {
            baseURL,
            withCredentials: false,
            headers: headers
        };
        return newConfig;
    },
    e => Promise.reject(e)

);

堆栈跟踪表明问题出在 dispatchXhrRequest 中。这里有一个对 toUpperCase 的调用:

https://github.com/axios/axios/blob/2ee3b482456cd2a09ccbd3a4b0c20f3d0c5a5644/lib/adapters/xhr.js#L28

看来你不见了 config.method

我的猜测是您需要将旧配置复制到新配置中,以便获得所有其他选项,例如 method:

const newConfig = {
  ...config,
  baseURL,
  withCredentials: false,
  headers: headers
};