这个别人封装好的axios代码
import axios from 'axios' axios.defaults.timeout \= 5000 axios.defaults.baseURL \= 'http://127.0.0.1:8000/' axios.defaults.headers\['Content-Type'\] = 'application/json' export default { fetchGet (url, params = {}) { return new Promise((resolve, reject) => { axios.get(url, params).then(res => { resolve(res.data) }).catch(error => { reject(error) }) }) }, fetchPost (url, params = {}) { return new Promise((resolve, reject) => { axios.post(url, params).then(res => { resolve(res.data) }).catch(error => { reject(error) }) }) }, fetchPut (url, params = {}) { return new Promise((resolve, reject) => { axios.put(url, params).then(res => { resolve(res.data) }).catch(error => { reject(error) }) }) }, fetchDelete (url, params = {}) { return new Promise((resolve, reject) => { axios.delete(url, params).then(res => { resolve(res.data) }).catch(error => { reject(error) }) }) } }
这个是请求数据的格式
import http from './public' // 获取首页轮播图 export const banner \=(params)=>{ return http.fetchGet('banner/',params) } // 手机发送验证码功能 export const sendcode \=(params)=>{ return http.fetchPost('codes/',params) } // 注册功能 export const userregister \=(params)=>{ return http.fetchPost('user/',params) } //收货地址功能 export const useraddress \= (params)=>{ return http.fetchPost('address/',params) }
请问我想在收货地址上添加headers的token属性,而不希望使用axios.defaults.headers\['Authorization'\] = 'JWT '+localStorage.getItem('token')来定义全局,因为注册功能不需要token请求头,那么我应该怎么在收货地址添加单独的headers呢
解决方法
fetchPost (url, params = {}, config = {}) { return new Promise((resolve, reject) => { axios.post(url, params, config).then(res => { resolve(res.data) }).catch(error => { reject(error) }) }) }, ... //收货地址功能 export const useraddress \= (params, config)=>{ return http.fetchPost('address/',params, config) } ... useraddress({}, { headers: { Authorization: 'JWT '+localStorage.getItem('token') } })
当然你也可以通过拦截器处理请求:
// 添加请求拦截器 axios.interceptors.request.use(function (config) { // 合并请求头 config.headers = Object.assign({}, config.headers, headers) return config; }, function (error) { // 处理错误请求 return Promise.reject(error); });
具体实现就根据自己项目需求,封装一下请求方法即可。