一、安裝axios
npm install axios
二、main.js中
import axios from 'axios';
Vue.prototype.$axios = axios;
axios.defaults.baseURL = '/api';
axios.defaults.headers.post['Content-Type'] = 'application/json';
三、vue.config.js
module.exports={
devServer:{
proxy:{
'/api': {
//target後面的url是自己服務器的url,我訪問的是.NET服務器的地址,
//如果沒有地址可以訪問百度、淘寶等
target: 'https://localhost:44340/AXIOS/Axios.aspx',
// 允許跨域
changeOrigin: true,
ws: true,
pathRewrite: {
'^/api': ''
}
}
}
}
}
四、向服務器發出請求
this.$axios.post('/').then(res => {
//ax是我自定義的變量,在服務器頁面中輸出url,這樣響應的數據中就有url了
this.ax = res.data.ax;
console.log(this.ax);
}).catch(err => {
console.log("請求失敗!",err);
})
五、使用fetch函數發送跨域請求
fetch(this.ax.loginurl,{
method:'post',
mode:'cors',
body:'username='+this.username+"&password="+this.password,
headers: new Headers({
'Content-Type': 'application/x-www-form-urlencoded'
})
}).then(res => {
if(res.ok){
res.json().then(data => {
console.log(data);
});
}
});