vue+axios跨域訪問
阿新 • • 發佈:2019-01-01
使用axios跨域訪問的時候瀏覽器報錯:
我的程式碼:
1.main.js配置:
2.在檔案中使用:import axios from 'axios'; axios.defaults.timeout = 5000;// 在超時前,所有請求都會等待 5 秒 axios.defaults.headers.post['Content-Type']= application/x-www-form-urlencoded;charset=UTF-8';// 配置請求頭 axios.defaults.baseURL = 'http://*******';// 配置介面地址 axios.defaults.withCredentials = false; Vue.prototype.$axios = axios;// 將axios配置成vue的原型
this.$axios.post('/', {
method: 'user.login',
mobile: this.username,
password: this.password,
sign: ''
}).then(function (response) {
console.log(response);
}).catch(function (error) {
console.log(error);
});
我們都以為是後端寫的有問題,找了很久,最後發現只需要將axios傳遞的json格式的資料轉換成string格式就可以了
this.$axios.post('/', JSON.stringify({//這裡將json格式轉成string格式傳送
method: 'user.login',
mobile: this.username,
password: this.password,
sign: ''
})).then(function (response) {
console.log(response);
}).catch(function (error) {
console.log(error);
});