node vue 跨域

小小兴奋下自己写的小项目终于过了跨域的这个坎。
其实无外乎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的)

  1. node中app.all接到请求,但是前段报404,没有调到“/login”,最后发现是地址写错了
  2. 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,成功后再发对应类型)
  3. node报错“first argument must be a string or buffer”,我把返回的json用JSON.stringify转一下就好了。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。