一、Fetch配置 https://blog.csdn.net/qq_42492055/article/details/82593692
1、在config配置文件中的index.js中的跨域區域中配置proxyTable
proxyTable: {
'/apis':{ //名字自己定義,以后接口的域名用他來替換
target: 'http://cc.lzjoy.com/', //接口域名
changeOrigin: true, //是否跨域
pathRewrite: {
'^/apis': '' //需要rewrite重寫
}
}
},
2、發起網絡請求
//1、get請求
created(){
console.log("請求數據")
fetch("/apis?urlparam=pad/index/getindexdata", {
method: "get",
headers:{
"Content-Type": "application/json",
},
}).then(result=>{
return result.json()
}).then(result=>{
console.log(result)
}).catch(err=>{
alert(err)
})
}
//2、post請求
created(){
console.log("請求數據")
fetch("/apis?urlparam=pad/index/getindexdata", {
method: "post",
headers:{
"Content-Type": "application/json",
},
//這里要放要上傳的參數
body: JSON.stringify({name: "abc", phone: "123456"})
}).then(result=>{
return result.json()
}).then(result=>{
console.log(result)
}).catch(err=>{
alert(err)
})
}
二、axios配置
https://blog.csdn.net/qq_42492055/article/details/82593692
0、安裝axios
npm install axios
1、在config配置文件中的index.js中的跨域區域中配置proxyTable
proxyTable: {
'/apis':{ //名字自己定義,以后接口的域名用他來替換
target: 'http://cc.lzjoy.com/', //接口域名
changeOrigin: true, //是否跨域
pathRewrite: {
'^/apis': '' //需要rewrite重寫
}
}
},
2、在程序入口 main.js文件中引入并配置axios
import Axios from 'axios'
// 設置axios
Vue.prototype.$axios = Axios
// Axios.defaults.baseURL = '/apis'
Axios.defaults.headers.post['Content-Type'] = 'application/json'
3、發起請求
//1、get請求
created(){
console.log("頁面加載")
this.$axios.get("/apis?urlparam=pad/index/getindexdata")
.then(res=>{
console.log(res)
alert(res)
})
.catch(err=>{
console.log(err)
})
}
//2、 post請求 name、phone是要發送的參數
created(){
this.$axios.post('/apis?urlparam=pad/index/getindexdata', {
name: 'Fred',
phone: '123456'
})
.then(function (response) {
console.log(response);
alert(response)
})
.catch(function (error) {
console.log(error);
});
}