jquery + node 通过 CORS 实现跨域访问
跨域有多种方式,现在的情况看来还是cors更适合一些,有很多优点,比如浏览器正式支持、支持post、可以控制跨域访问的网站等。
SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。
我们来看看node如何实现cors方式的跨域。在网上找到了一些代码,考过来之后运行报错,可能这个是在express里面的写法吧,那么原生的写法是什么样子的呢?又找了半天,并且经过测试得到了原生的写法:
express的写法:
---app.js--- app.all('*', function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With"); res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS"); res.header("X-Powered-By",' 3.2.1') if(req.method=="OPTIONS") res.send(200);/*让options请求快速返回*/ else next(); });
node原生写法:
var http = require("http"); http.createServer(function (req, res) { var a={ "a1":"www" }; res.setHeader("Access-Control-Allow-Origin", "*"); res.setHeader("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With,xToken"); res.setHeader("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS"); res.writeHeader(200, {'Content-Type': 'application/json'}); res.write(JSON.stringify(a)); res.end(); }).listen(8080);
需要先用 setHeader 进行设置,最后再用 writeHeader 进行设置。这样就可以了。
然后就是客户端的写法了,由于客户端使用的框架不同,设置方式也有点差别,这里先介绍一下比较基本的jQuery的方式。
$.ajax({ type: "POST", //post方式 dataType: "JSON", //json格式的数据 cache: false, //客户端不缓存 //headers: { //自定义头 // xtoken: "1234qwert" //}, xhrFields: { //允许跨域访问时添加cookie withCredentials: false //true "Access-Control-Allow-Origin" 不能写* ;false可以写 * }, //crossDomain: true, url: "http://127.0.0.1:8080/1234", data: {"a":"11"}, //json格式的数据 //timeout: 2000, error: function (request, textStatus, errorThrown) { //访问失败,自动停止加载动画,并且给出提示 alert("提交的时候发生错误!"); }, success: function (data) { $("#div").html(data.a1); } });
这里的 xhrFields 设置比较郁闷,浏览器的管理越来越严格了。

更多精彩