一、首先安装npm安装axios
$ npm i axios -S
二、配置vue-cli->config->index->proxyTable
proxyTable: {
"/api":{
target:"http://api.douban.com",
changeOrigin:true,
pathRewrite:{
"^/api":""
}
}
}
三、配置main.js文件
// 在vue中全局引入axios
import axios from 'axios'
// 全局定义跨域请求域名
//axios.defaults.baseURL = '/api'
// 挂载到vue的原型上
Vue.prototype.$axios = axios
四、在created生命周期函数中请求方式
//get方式请求
this.$axios.get("/api/v2/movie/top250",{
// 请求配置
params:{
start:0,
count:10
}
})
.then(response =>{
console.log(response.data)
})
.catch(error =>{
console.log(error)
})
//post方式请求
this.$axios.post("/api/v2/movie/top250",{
start:0,
count:10
})
.then(response =>{
console.log(response.data)
})
.catch(error =>{
console.log(error)
})
//axios Api请求
this.$axios({
method:"post",
baseURL:"/api",
data:{
start:0,
count:10
},
url:'/v2/movie/coming_soon'
})
.then(response =>{
console.log(response.data)
})
.catch(error =>{
console.log(error)
})
注意:
baseURL中的api即为index.js中的target值,因此,axios请求的地址实际是http://api.douban.com/v2/movie/top250执行的结果: