node vue 跨域

小小興奮下自己寫的小項目終于過了跨域的這個坎。
其實無外乎header加上各種允許,但是任就會有奇奇怪怪的問題出現(xiàn)。

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'};//返回的數(shù)據(jù)
    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 繼續(xù)請求;如果不是,阻止請求
    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("傳入?yún)?shù)-->" + JSON.stringify(config.params));
        } else {
            console.log("傳入?yún)?shù)-->" + config.data);
        }
    }
    return config;
}, function(error) {
    return Promise.reject(error);
});

//響應(yīng)攔截器
axios.interceptors.response.use(
    response => {
        if(showLogs === 1) {
            console.log("返回數(shù)據(jù)-->" + 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的)

  1. node中app.all接到請求,但是前段報404,沒有調(diào)到“/login”,最后發(fā)現(xiàn)是地址寫錯了
  2. node報錯“invalid media type”,axios post默認是"Content-Type", "application/x-www-form-urlencoded"),手賤改成了“application/json”(據(jù)說Access-Control-Allow-Methods不能為*,要寫"get,post,put,delete,option",改了Content-Type后會先發(fā)一條option,成功后再發(fā)對應(yīng)類型)
  3. node報錯“first argument must be a string or buffer”,我把返回的json用JSON.stringify轉(zhuǎn)一下就好了。
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容