vue-cli axios請求方式以及跨域處理
-
安裝axios
cnpm install axios --save -
在要使用axios的文件中引入axios
1.main.js文件 :import axios from 'axois' 2.要發送請求的文件:import axios from 'axois' -
在config/index.js文件設置代理
dev: { proxyTable: {// 輸入/api 讓其去訪問http://localhost:3000/api '/api':{ target:'http://localhost:3000'//設置調用的接口域名和端口號 ( 設置代理目標) }, '/api/*':{ target:'http://localhost:3000' }, changeOrigin: true, pathRewrite: { //路徑重寫 '^/api': '/' //這里理解成用‘/api’代替target里面的地址,后面組件中我們掉接口時直接用api代替 比如我要調用'http://localhost:3002/user/add',直接寫‘/api/goods/add’即可 } } 試一下,跨域成功,但是這知識開發環境(dev)中解決了跨域問題,生產環境中正真部署到服務器上如果是非同源還是存在跨域問題。
axios請求方式
Get請求
// 向具有指定id的用戶發出請求
axios.get('/user?id=1001')
.then(function (response) {
console.log(response.data);
}).catch(function (error) {
console.log(error);
});
// 也可以通過 params 對象傳遞參數
axios.get('/user', {
params: {
id: 1001
}
}).then(function (response) {//請求成功回調函數
console.log(response);
}).catch(function (error) {//請求失敗時的回調函數
console.log(error);
});
post請求
axios.post('/user', {
userId: '10001' //注意post請求發送參數的方式和get請求方式是有區別的
}).then(function (response) {
console.log(response);
}).catch(function (error) {
console.log(error);
});
