axios 是一个基于Promise 用于浏览器和 nodejs 的 HTTP 客户端
npm install axios
进行安装
之后我创建了http.js
来引用
import axios from 'axios'
const service = axios.create({
baseURL: "http://localhost", // url = base url + request url
withCredentials: false, // send cookies when cross-domain requests 跨域要设置成false
timeout: 5000 // request timeout
})
- 设置请求拦截器
service.interceptors.request.use(
config => {
// 不传递默认开启loading
if (config.method === 'post' || config.method === 'put') {
// post、put 提交时,将对象转换为string, 为处理Java后台解析问题
// config.data = JSON.stringify(config.data)
}
config.headers.authentication = 'token:'+getToken()
return config
},
error => {
// do something with request error
console.log(error) // 打印错误
return Promise.reject(error)
}
)
- 设置响应拦截器
service.interceptors.response.use(
response => {
const res = response.data
if (res.status && res.status !== 200) {
//拦截错误
return Promise.reject(res || 'error')
} else {
setToken(res.headers.authentication)
return Promise.resolve(res)
}
},
error => {
return Promise.reject(error)
}
)
- 对常用的请求方式进行封装
export function get(url, params, headers) {
const options = {}
if (params) {
options.params = params
}
if (headers) {
options.headers = headers
}
return service.get(url, options)
}
export function post(url, data, params, headers) {
const options = {}
if (params) {
options.params = params
}
if (headers) {
options.headers = headers
}
return service.post(url, data, options)
}
export function put(url, params, headers) {
const options = {}
if (headers) {
options.headers = headers
}
return service.put(url, params, options)
}
export function del(url, params, headers){
const options = {}
if (params) {
options.params = params
}
if (headers) {
options.headers = headers
}
return service.delete(url, options)
}
export default service
- token的一些操作
const TokenKey = 'LocalToken';
export function getToken() {//获取TokenKey值
return window.localStorage.getItem(TokenKey)
}
export function setToken(tokenData) {//设置TokenKey值
return localStorage.setItem(TokenKey, JSON.stringify(tokenData))
}
export function removeToken() {//
return window.localStorage.removeItem(TokenKey)
}