Node.js开发 ---- 设置HTTP响应头解决跨域

来源:互联网 发布:ratpack java 编辑:程序博客网 时间:2024/06/06 02:59

本地localhost跨域连接nodejs服务器数据时Chrome报错:

XMLHttpRequest cannot load http://24px.cc/……. No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://localhost’ is therefore not allowed access.

解决办法:

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

也可以直接引入cors

npm install cors

//app.jsvar cors = require('cors');app.use(cors());

复习一下header头三件套

header(‘Access-Control-Allow-Origin :’.$origin); //允许的域名( * 所有域)
header(‘Access-Control-Allow-Methods : POST’); //允许的方法
header(‘Access-Control-Allow-Headers : x-requested-with , content-type’); //服务器支持的头信息

参考:
HTTP访问控制(CORS)
从原理分析CORS——我们到底是怎么跨域的
HTTP消息头(HTTP headers)-常用的HTTP请求头与响应头

0 0
原创粉丝点击