在 VueJS 中配置 Get、Post、Patch 全局标头的最佳方法

2023-11-23

我是 VueJs 的新手,我正在寻找在 VueJS 中为 Get、Post、Patch 配置全局标头的最佳方法,即使用方便、安全性强。目前我只是把它写在export default {}对于每个组件,我知道这非常糟糕。所以我请求你们帮忙。

感谢@Hardik Satasiya 修复

〜/插件/axios.js

每个组件:

import axios from 'axios'

var api = axios.create({
  baseURL: 'http://localhost:8000/api/v1/',
  headers: {'Authorization': 'JWT ' + store.state.token}
})

export default api

问题:无法将 store 传输到 axios.create,所以store is not defined


是的,使用它是个好主意axios因为它的回购协议得到维护。

您可以为此使用全局配置

import axios from 'axios';

axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

OR best方法是创建单独的instances为此(如果您正在使用multiple api在同一时间)

import axios from 'axios';

var myApi = axios.create({
  baseURL: 'https://my-domain.com/api/',
  timeout: 1000,
  headers: {'X-Custom-Header': 'CustomHeader1'}
});

// another api service
var amazonApi = axios.create({
  baseURL: 'https://amazon-domain.com/api/',
  timeout: 2000,
  headers: {'X-Custom-Header': 'CustomHeader2'}
});

export default {
    myApi,
    amazonApi
}

所以你可以使用api分开,没有任何冲突。

如果您要设置 auth 标头,最好不要在实例创建时设置它,而是可以在您的实例中设置它ready callback所以你可以从localStorage或者从第三方获取即可设置。

创建后更改标题

myApi.defaults.headers.authorization = 'JWT ' + yourToken;

因此,当您确定有令牌时,您可以从任何部分设置标头,然后您可以使用此代码来设置标头。 如果您已经通过请求获得了标头,您也可以使用此代码来设置它。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 VueJS 中配置 Get、Post、Patch 全局标头的最佳方法 的相关文章

随机推荐