# axios
# axios 使用
- axios 的 get 请求 入参必须放在 { params: { data } }
- 创建单个实例 axios.create
- 请求前拦截函数:axios.interceptors.request.use
- 响应后拦截函数:axios.interceptors.response.use
# 特性
- 从浏览器中创建 XMLHttpRequests (opens new window)
- 从 node.js 创建 http (opens new window) 请求
- 支持 Promise (opens new window) API
- 拦截请求和响应
- 转换请求数据和响应数据
- 取消请求
- 自动转换 JSON 数据
- 客户端支持防御 XSRF
# 安装
使用 npm:
npm install axios
使用 bower:
bower install axios
使用 cdn:
< script src = "https://unpkg.com/axios/dist/axios.min.js" / >
# Axios 实战实例
# 创建一个实例进行配置
- src/utils/request.js
const ips = {
development: "http://localhost:3000", //测试接口
production: "http://127.0.0.1:3000", // 线上接口
};
// 公共的url地址
const Axios = axios.create({
// 开发环境中使用测试接口 生产环境中使用线上接口
baseURL: ips[process.env.NODE_ENV],
withCredentials: true, // 携带cookie到服务器
timeout:20000 //设置超时 时间
});
//设置post请求头
Axios.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded;charset=UTF-8";
// 请求拦截
Axios.interceptors.request.use(config => {
return config
})
// 相应拦截
Axios.interceptors.response.use(response => {
return response
})
export default Axios
- 请求函数封装
import axios from '../utils/request.js'
GET: 从服务器读取数据
const Get = (value) => {
return axios.get('/text', { params: value }).then(res => {
return res
}).catch(err => {
throw err
})
}
export { Get }
POST: 向服务器添加新数据 / 从服务器读取数据
const Post = (value) => {
return axios.post('/shop',value).then(res => {
return res
}).catch(err => {
throw err
})
}
export { Post }
PUT: 更新服务器数据
DELETE: 删除服务器数据
# 请求头携带 token 值
const createToken = (config) => {
// token值是vuex里的token
let token = Store.state.users.token;
// 将token放在请求头里
config.headers.common["Authorization"] = token;
return config;
};
// 请求拦截器
Axios.interceptors.request.use(
(config) => {
// token 不存在与注册和登录 退出需要
if (config.url === "/user/login" && config.data.state === 0) {
// 配置token
// 将token 添加到请求头
return createToken(config);
}
if (config.url === "/user/login" || config.url === "/user/register") {
return config;
}
// 配置token
return createToken(config);
},
(error) => Promise.reject(error)
);
// 响应拦截器
Axios.interceptors.response.use(
(response) => {
if (response.status === 200 && response.data.code) {
return response.data;
} else {
// 如果令牌过期了,将vuex里的token改值,路由跳到登录里
if (response.data.data.token === false) {
message.error(response.data.msg || "token过期了");
// 调用vuex里的setUser方法修改token值
Store.commit("setUser", {
token: null,
loginState: 0
});
Router.replace("/user");
} else {
message.error("接口错误");
}
return {
code: 0
};
}
},
(error) => Promise.reject(error)
);