適用於vue-cli3以上版本搭建的項目
一、接口基址(單個接口地址)
如果你的項目只有一個服務器訪問地址(接口地址),不調用別的接口地址的話可以直接在src下的main.js中設置axios的默認基址
//main.js中
import axios from 'axios'
Vue.prototype.$axios = axios
axios.defaults.baseURL='http://localhost:3000';//設置基址
例子如下
//example.vue
<template>
<div></div>
</template>
<script>
export default {
name: 'example',
data(){
return{
}
},
mounted(){
this.login()
},
methods:{
//登錄接口
login(){
this.$axios.post('/login',{
id:111,
psw:'1111111'
}).then(res=>{
console.log(res)
})
}
}
}
</script>
二、代理接口地址
如果你的項目需要訪問多個地址,即調用多個不同的接口來進行數據的交互,這個時候應該設置代理地址
在項目根目錄下新建一個vue.config.js文件
//vue.config.js
module.exports = {
devServer: {
host: 'localhost',
port: 8080,//本地運行的端口
open: true, //配置自動啓動瀏覽器
hotOnly:false,
//接口代理
proxy: {
'/news': {
target: 'http://v.juhe.cn/toutiao',//設置要代理訪問的接口---這是頭條的接口
changeOrigin: true,
pathRewrite: {
'^/news': ''//重寫訪問地址,在請求時可以省略target的地址,直接以/news開頭
}
},
'/api': {
target: 'http://localhost:3000',//設置要代理訪問的接口----這是我自己的接口
changeOrigin: true,
pathRewrite: {
'^/api': '' //重寫訪問地址,在請求時可以省略target的地址,直接以/api開頭
}
}
}
},
例子如下
//example.vue
<template>
<div></div>
</template>
<script>
export default {
name: 'example',
data(){
return{
}
},
mounted(){
this.login()
this.getnews();
},
methods:{
getnews(){
//獲取頭條信息
this.$axios.get('/news/index',{params:{
key:'d2f47f5d5981c66091cfa284cecfd781',
type:'頭條'
}}).then(res=>{
console.log(res)
})
},
//登錄接口
login(){
this.$axios.post('/api/login',{
id:111,
psw:'111111'
}).then(res=>{
console.log(res)
})
}
}
}
</script>