npm install axios --save
main.js中加入如下内容
// 引入axios ---------------------------------------------------
import axios from 'axios'
Vue.prototype.$axios = axios
Vue.prototype.$axios.defaults.baseURL = 'http://127.0.0.1:8000/' // 请求根路径
// -------------------------------------------------------------
this.$axios.get('index').then(res => {
// 返回数据在 res.data 中
})
this.$axios.post('login', {user:"admin", pwd:"123"}).then(res => {
// 返回数据在 res.data 中
})
var res1 = this.$axios.get('index')
var res2 = this.$axios.post('login', {user:"admin", pwd:"123"})
this.$axios.all([res1, res2]).then(this.$axios.spread(res1, res2) => {
// 两个请求的返回结果在 res1 和 res2 中
})
src/request/index.js
// 引入
import Axios from 'axios'
import { Message } from 'element-ui' // 需要装个 element-ui,错误提示界面友好一些
// 前端存在 localStorage 中的 token
const token = localStorage.getItem('token')
// 实例化
const request = Axios.create({
baseURL: "http://127.0.0.1:8000/", // 服务根路径
timeout: 200000, // 请求过期时间
headers: {
Authorization: token // token 插入请求头给后端校验
}
})
// 拦截后端返回的请求
request.interceptors.response.use(res => {
if (res.status !== 200) {
Message.error("something err...") // 返回错误的提示信息
}
return res.data // 只取 res 中的 data,后续取值不需要再写一层 data 了
})
// 导出
export default request
main.js中改成如下内容
// 引入axios ---------------------------------------------------
import request from './request'
Vue.prototype.$http = request
// -------------------------------------------------------------
this.$http.get('index').then(res => {
// 返回数据在 res.data 中
})
this.$http.post('login', {user:"admin", pwd:"123"}).then(res => {
// 返回数据在 res.data 中
})
var res1 = this.$http.get('index')
var res2 = this.$http.post('login', {user:"admin", pwd:"123"})
this.$http.all([res1, res2]).then(this.$http.spread(res1, res2) => {
// 两个请求的返回结果在 res1 和 res2 中
})