1.新建公共请求JS例如api.js;
2.在api.js引入
`import axios from 'axios'
import { Message } from 'element-ui`
const http = axios.create({
baseURL: '后端接口前缀',
// baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
// withCredentials: true, // send cookies when cross-domain requests
timeout: 50000
// request timeout
})
// 设置 post、put 默认请求头 Content-Type
http.defaults.headers.post['Content-Type'] = 'application/json'
http.defaults.headers.put['Content-Type'] = 'application/json'
// request interceptor 请求拦截(请求发出前处理请求)
http.interceptors.request.use(
config => {
// do something before request is sent
return config
},
error => {
// do something with request error
console.log(error) // for debug
return Promise.reject(error)
}
// 封装get方法
export function get({ url, params }) {
return new Promise((resolve, reject) => {
http.get(url, {
params: params
}).then(res => {
resolve(res.data)
}).catch(err => {
reject(err.data)
})
})
}
// 封装post方法
export function post({ url, data }) {
return new Promise((resolve, reject) => {
http.post(url, data).then(res => {
resolve(res.data)
}).catch(err => {
reject(err.data)
})
})
}
3.新建页面请求的JS例如http.js
4.在http.js中引入api.js
import { get, post } from './http' // 导入axios实例文件中方法
import { get, post } from './http' // 导入axios实例文件中方法
const server = {
//带参数的 get 方法
以下为页面请求的数据接口
getById(param) {
return get({
url: '/role/getById',
method: 'get',
params: param
})
}
//不带参数的 get 方法
getAll() {
return get({
url: '/role/getAll',
method: 'get'
})
},
// post 方法
login(param) {
return post({lo
url: '/role/save',
method: 'post',
data: param
})
}
}
export default server
5.在页面引入http.js
import apis from '@/api/http'
6.在页面使用api
带参数的请求
try {
let data={
name:this.userName,
password:this.password
}
apis.login(data).then((res)=>{
Cookies.set('token',res);
that.$store.commit('login',res)
that.$router.push({path:'/index'})
})
} catch (e) {
Message({
message:'服务端错误',
type: 'warning',
center:true,
duration: 1 * 1000
});
}
不带参数的请求
apis.getAll().then((res)=>{
})