【问题标题】:How to prevent Axios from adding slash after baseURL如何防止axios在baseURL后面加斜杠
【发布时间】:2020-05-13 14:48:57
【问题描述】:

在我的 Vue 应用程序中,我将 axios 配置放入单独的文件 config.js

config.js的内容

import axios from "axios";
const token = localStorage.getItem('user-token');
const baseUrl = `/api/v2.1/document.json&token=${token}&`;

export default () => {
    return axios.create({
        baseURL: baseUrl
    })
}

在我的 Vuex 商店模块 formFields.js 我有:

import Api from '../../api/config';

...

const actions = {
    async getApiFields() {
        await Api().get('type=documentType').then(function(response){
            console.log(response);
        }).catch(e => {
            this.errors.push(e)
        });
    }
};

那么,有什么问题吗?不知道axios为什么要加'/'

请求URL:... / API / V2.1 / document.json&标记= eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiI3ZTE2OTk5My00YTJiLTRhYWMtOGNiNi00ZTY0NGY2NjE3NTkiLCJhdWQiOiJNYWVzdHJvTElWRSIsInN1YiI6Ik1hZXN0cm9MSVZFIEFQSSIsImV4cCI6MTU4MDIwMTQ5OSwiaWF0IjoxNTgwMTk3NzE5fQ.PWstAQCDr6Atd_J26futucIBOBUZiFCcp0g5Y1JTYUs&/键入= documentType P>

Network tab screenshot here

如何防止添加这个斜线?

【问题讨论】:

  • 也许您应该为您的参数使用实际的查询字符串?
  • 感谢@04FS,我想停止在我执行 axios 请求的每个文件中从 localStorage 读取令牌(如果可能的话)。
  • 我说的是您的 baseUrl,您似乎正试图将可能应该是查询字符串参数的内容填充到 URL 路径中。
  • 首先我认为端点/document.json 不应该是baseURL 的一部分。其次,您需要找到一种方法来组合默认查询 (token) 和附加请求查询 (type)。一种解决方案是使用 axios 拦截器。看看我的回答。

标签: vue.js axios prefix slash base-url


【解决方案1】:

tl;dr 使用 axios 拦截器

组合默认和附加查询参数的问题

axios.create 的配置对象中使用字段params,例如

import axios from "axios";
const token = localStorage.getItem('user-token');
const baseUrl = `/api/v2.1/`

/* Please note, an endpoint should not be part of the BaseURL */

export default () => {
  return axios.create({
    baseURL: baseUrl,
    params : { token : token }
  });
}

/* this will add ?token="XXX" query parameter to the url
import Api from '../../api/config';

/* /document.json is your endpoint, and should not be part of the baseUrl */

const actions = {
  async getApiFields() {
    await Api().get('/document.json').then((response) => {
      console.log(response);
    }).catch(e => {
      this.errors.push(e)
    });
  }
};

问题在于您不能添加额外的查询参数,因为它们会覆盖默认参数。所以要解决这个问题,你可以添加一个 axios 拦截器,它将令牌查询参数添加到每个请求中。

解决方法:使用axios拦截器

import axios from "axios";
const token = localStorage.getItem('user-token');
const baseUrl = `/api/v2.1/`

const instance = return axios.create({ baseURL: baseUrl });
instance.interceptors.request.use(config => {
  config.params = {
   // add your default ones
   token: token,
   // spread the request's params
    ...config.params,
  };
  return config;
});
export default instance; 
import Api from '../../api/config';

const actions = {
  async getApiFields() {
    await Api().get('/document.json', {params:{type:'documentType'}})
    .then((response) => {
      console.log(response);
    }).catch(e => {
      this.errors.push(e)
    });
  }
};

使用像这样的拦截器,会产生这样的请求(在这个例子中):

/api/v2.1/document.json?token=XXX&type=documentType

您可以在此处阅读有关 拦截器 的更多信息:https://github.com/axios/axios#interceptors

【讨论】:

  • 饼干就是这样崩溃的:) 谢谢。完美的解决方案!
  • 很高兴我能帮上忙
  • @czesi0 如果答案正确并帮助了你,请接受作为答案,谢谢! :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-04-18
  • 2015-06-29
  • 1970-01-01
  • 2021-08-24
  • 1970-01-01
  • 2012-09-06
相关资源
最近更新 更多