vue跨域问题

如何解决vue-resource中出现的Failed to load http://localhost:8000/index: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response。

问题描述:

在配置服务器时设置res.header("Access-Control-Allow-Headers", "X-Requested-With")

vue跨域问题

在vue中发送请求:

vue跨域问题

结果执行后发现:

vue跨域问题

意思是:请求标题字段Content-Type在预检响应中不被Access-Control-Allow-Headers所允许

经过反复的测试后,发现浏览器是会先发一次options请求,如果请求通过,则继续发送正式的post请求,而如果不通过则返回以上错误

解决办法:在服务器配置header,代码如下

app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Connection, User-Agent, Cookie");
    res.header("Access-Control-Allow-Methods", "POST,GET");
    res.header("X-Powered-By", ' 3.2.1')
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
})

上面的代码加入允许的header后,再在vue中发送请求就能正常执行了