参考:https://www.cnblogs.com/anna001/p/14793957.html
axios官网:https://www.npmjs.com/package/axios
axios请求格式:
一. get和post传参的区别
GET
1.url拼接
axios.get('/login?name=admin')
2.params传参
axios.get('/login', {
params:{
name: 'admin',
}
})
POST
1.params传参
axios.post('/login', {
params:{
name: 'admin',
}
})
2.data传参
axios({ method: 'post', url: '/login', data: { name: 'admin', } });
也可省略data,直接传参
axios.post('/login', { name: 'admin', })
二. 具体使用
封装axios的https.js
... // 统一请求超时时间 axios.defaults.timeout = 10000; ... export function get(url, params, config) { return new Promise((resolve, reject) => { axios .get( url,
// 关键,合并两个对象 Object.assign( {}, { params: params, }, config ) ) .then((res) => { resolve(res.data); }) .catch((err) => { reject(err.data); }); }); } export function post(url, params, config) { return new Promise((resolve, reject) => { axios .post(url, params, config) .then((res) => { resolve(res.data); }) .catch((err) => { reject(err.data); }); }); } ...
统一配置请求的api.js
import { get, post } from './http.js'; // 登录 export const userLogin= (params) => get('/login', params, { timeout: 12000, }); // 登出 export const userLogout = (params) => post('/logout', params, { timeout: 12000, headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, });
页面中使用
... <script> import { userLogin, userLogout} from 'api/api'; ... methods:{ loginFun(){ userLogin({name: 'admin'}) .then((res) => { ... }) }, logoutFun(){ userLogout({name: 'admin'}) .then((res) => { ... }) } } ... </script> ...