一、安装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);
});
}
});