nodejs express框架解决跨越问题

XMLHttpRequest cannot load http://192.168.1.140:8080/users?. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. index.html:1

XMLHttpRequest cannot load http://192.168.1.140:8080/profile. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. index.html:1


访XmlHttpRequest。但是,有些时候我们需要通过跨域访问来获取一些资源,例如:


    •作为用户,我们需要在自己的网站用AJAX调用一些其他网站提供的服务,这些服务常常是一些HTTP GET形式的APIAJAX的基础是XmlHttpRequest跨域的XmlHttpRequest是不被允许的„„ 


    •作为服务提供者,我们想让用户只是简单的在他们的网页中远程引用我们的脚本文件,并加入一些少量的html代码就能使用我们的服务,而不用在服务器端做任何的改变。当然,XmlHttpRequest也是行不通的。



在nodejs加上express框架在服务器代码app.js文件中加入下面的跨域允许权限: (注意:下面这个要放到post和get请求前面)
        app.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();
        });
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值