axios 的使用
npm install axios -S
创建tools文件 axios请求拦截器
import axios from 'axios'
// 自定义axios
const myaxios = axios.create({
baseURL: 'http://121.5.59.4/api',
timeout: 10000
})
// 拦截请求,携带token数据
myaxios.interceptors.request.use(function (config) {
config.headers.token = localStorage.getItem('token')
// console.log(config)
return config
}, function (error) {
// Do something with request error
return Promise.reject(error)
})
// 拦截响应,登录守卫
myaxios.interceptors.response.use(function (response) {
const url = response.config.url
if (response.data.code === 400) {
// console.log(response.config.url)
// console.log('登录失效,需要重新登录')
if (url.includes('cart')) {
location.href = '/login?to=/cart'
} else if (url.includes('order')) {
location.href = '/login?to=/order'
} else if (url.includes('user')) {
location.href = '/login?to=/my'
} else if (url.includes('search')) {
location.href = '/login?to=/search'
}
}
return response
}, function (error) {
// Do something with response error
return Promise.reject(error)
})
export default myaxios
引入设置好的baseUrl 配置文件
import axios from '../tools/index.js'
封装请求
export function getdata () {
return axios.get('http://localhost:3000/api/pro/sort')
}
文件引入 封装 请求数据
import { getBanner } from '../request/axios.js'
getdata().then(data => {
console.log(data)
})