vue中使用axios實現跨域請求
阿新 • • 發佈:2019-02-19
一、首先安裝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執行的結果: