小小興奮下自己寫的小項目終于過了跨域的這個坎。
其實無外乎header加上各種允許,但是任就會有奇奇怪怪的問題出現。
node+express vue+axios
安裝什么的就過了
node的地址是http://127.0.0.1:8081
vue的地址是http://localhost:1111,所以跨域啦~~~
node加上
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");//http://localhost:1111就是vue的地址
res.header("Access-Control-Allow-Headers", "*");
res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
res.header("X-Powered-By",' 3.2.1')
res.header("Content-Type", "*");//“application/x-www-form-urlencoded”
next();
});
app.post('/login', urlencodedParser, function (req, res) {
console.log(req.body)
var senddata={code: 200, msg: 'done'};//返回的數據
res.end(JSON.stringify(senddata));
})
app.get('/login', function (req, res) {
console.log(JSON.stringify(req.query))
var senddata={code: 200, msg: 'done'};
res.end(JSON.stringify(senddata));
})
vue 中
//登錄
loginSubmit(){
let that=this;
axios.ajaxPost('/login',this.loginForm,function (res) {
console.log(res)
});
}
//axios
axios.defaults.baseURL = 'http://127.0.0.1:8081/'
export const ajaxPost = function(url, params, callback, err) {
console.log("post")
axios({
method: 'post',
url: url,
data: Qs.stringify(params)
}).then(function(res) {
callback(res);
}).catch(function(error) {
if(err) {
callback('error');
}
});
};
export const ajaxGet = function(url, params, callback, err) {
axios.get(url, {
params: params
}).then(function(res) {
callback(res);
}).catch(function(error) {
if(err) {
callback('error');
}
});
};
//請求攔截器
axios.interceptors.request.use(function(config) {
//判斷是不是登錄接口,如果是登錄接口 不需要token 繼續請求;如果不是,阻止請求
if(config.url.indexOf('login') > -1) {
// config.url=prePath+config.url;
//continue
} else {
if(getCookie('access_token')) { // 判斷是否存在token,如果存在的話,則每個http header都加上token
config.headers.Authorization = getCookie('access_token');
} else {
return Promise.reject();
}
}
if(showLogs === 1) {
console.log("接口地址-->" + config.url);
if(config.params) {
console.log("傳入參數-->" + JSON.stringify(config.params));
} else {
console.log("傳入參數-->" + config.data);
}
}
return config;
}, function(error) {
return Promise.reject(error);
});
//響應攔截器
axios.interceptors.response.use(
response => {
if(showLogs === 1) {
console.log("返回數據-->" + JSON.stringify(response.data));
}
if(response.config.url.indexOf('chackUser') > -1) {//如果是登錄接口,不處理異常
}else{
var code = response.data.code;
if(code && code !== 200) {
if(code === 401) { //401 未登錄
delCookie('access_token');
window.location.reload();
} else {
Message.error(response.data.msg);
}
return Promise.reject(response.data);
}
}
return response.data;
},
error => {
return Promise.reject(error)
});
post,get請求及返回
順便提下遇到的各種問題(都是很250的)
- node中app.all接到請求,但是前段報404,沒有調到“/login”,最后發現是地址寫錯了
- node報錯“invalid media type”,axios post默認是"Content-Type", "application/x-www-form-urlencoded"),手賤改成了“application/json”(據說Access-Control-Allow-Methods不能為*,要寫"get,post,put,delete,option",改了Content-Type后會先發一條option,成功后再發對應類型)
- node報錯“first argument must be a string or buffer”,我把返回的json用JSON.stringify轉一下就好了。