欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Express学习笔记

程序员文章站 2022-08-28 15:59:10
如何解决vue-resource中出现的Failed to load http://localhost:8000/index: Request header field content-type is not allowed by Access-Control-Allow-Headers in pr ......

如何解决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")

Express学习笔记

  在vue中发送请求:

Express学习笔记

结果执行后发现:

Express学习笔记

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

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

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

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

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