nodejs前端跨域访问

nodejs前端跨域访问

XMLHttpRequest cannot load http://localhost:3000/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

上面是我学习nodejs中碰到的一个异常,下面有代码以及解决方案。

1)js文件代码

var http=require('http');
var querystring=require('querystring');

http.createServer(function(req,res){
  var postData='';
  req.setEncoding('utf8');

  req.on('data',function(chunk){
    postData+=chunk;
  });
  req.on('end',function(){
    res.end(postData+"hehe");
  });
}).listen(3000);
console.log("服务启动。。。")

 

2)前端html页面代码

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script src="jquery-1.8.3.js"></script>
<script type="text/javascript">
$(function(){
  $("#test").click(function(){
    $.ajax({
      'url':'http://localhost:3000',
      'method':'POST',
      'data':{},
      'success':function(data){
        console.log(data);
      }
    });
  });
})
</script>
</head>
<body>
<p id="test">click me</p>
</body>
</html>

这是一个简单的ajax访问nodejs服务器demo,我的服务运行在windows10系统上。

win键+R 输入CMD 调出命令行工具,输入:node -v    查看是否安装了nodejs以及版本。

通过cd命令定位到js文件所在目录,输入:node js文件名    运行js文件

谷歌浏览器打开html文件点击click me然后按F12发现上文所说错误。

 

解决思路,百度一下发现是ajax跨域访问问题

在createServer方法里面第一行设置 res.setHeader('Access-Control-Allow-Origin', '*');

*号代表允许任何与的请求,当然实际生产环境不可能这么做。

你可以通过报错提示找到被拒绝的域然后设置res.setHeader('Access-Control-Allow-Origin', '域名');

比如我在HBulider里面打开html文件是这样设置res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8020');

在本地直接打开html文件可以这样子设置res.setHeader('Access-Control-Allow-Origin', 'null');

 

http://wishing.vip/ 这是我的移动端博客网址,里面有很多H5的实例。

会java或者c#等服务端语言的可以对比下

nodejs搭建一个web服务的是多么简单,不需要tomcat等http服务器,因为它内置了一个http服务器。

 

设置允许所有域名跨域:
app.all("*",function(req,res,next){
    //设置允许跨域的域名,*代表允许任意域名跨域
    res.header("Access-Control-Allow-Origin","*");
    //允许的header类型
    res.header("Access-Control-Allow-Headers","content-type");
    //跨域允许的请求方式 
    res.header("Access-Control-Allow-Methods","DELETE,PUT,POST,GET,OPTIONS");
    if (req.method.toLowerCase() == 'options')
        res.send(200);  //让options尝试请求快速结束
    else
        next();
}
1
2
3
4
5
6
7
8
9
10
11
12
设置允许指定域名“http://www.zhangpeiyue.com”跨域:
app.all("*",function(req,res,next){
    //设置允许跨域的域名,*代表允许任意域名跨域
    res.header("Access-Control-Allow-Origin","http://www.zhangpeiyue.com");
    //允许的header类型
    res.header("Access-Control-Allow-Headers","content-type");
    //跨域允许的请求方式 
    res.header("Access-Control-Allow-Methods","DELETE,PUT,POST,GET,OPTIONS");
    if (req.method.toLowerCase() == 'options')
        res.send(200);  //让options尝试请求快速结束
    else
        next();
}
1
2
3
4
5
6
7
8
9
10
11
12
设置允许多个域名跨域:
app.all("*",function(req,res,next){
    if( req.headers.origin.toLowerCase() == "http://www.zhangpeiyue.com"
        || req.headers.origin.toLowerCase() =="http://127.0.0.1" ) {
        //设置允许跨域的域名,*代表允许任意域名跨域
        res.header("Access-Control-Allow-Origin", req.headers.origin);
    }
    //允许的header类型
    res.header("Access-Control-Allow-Headers", "content-type");
    //跨域允许的请求方式 
    res.header("Access-Control-Allow-Methods", "DELETE,PUT,POST,GET,OPTIONS");
    if (req.method.toLowerCase() == 'options')
        res.send(200);  //让options尝试请求快速结束
    else
        next();    
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
如果允许的域名较多,可以将允许跨域的域名放到数组当中:
app.all("*",function(req,res,next){
    var orginList=[
        "http://www.zhangpeiyue.com",
        "http://www.alibaba.com",
        "http://www.qq.com",
        "http://www.baidu.com"
    ]
    if(orginList.includes(req.headers.origin.toLowerCase())){
        //设置允许跨域的域名,*代表允许任意域名跨域
        res.header("Access-Control-Allow-Origin",req.headers.origin);
    }
    //允许的header类型
    res.header("Access-Control-Allow-Headers", "content-type");
    //跨域允许的请求方式
    res.header("Access-Control-Allow-Methods", "DELETE,PUT,POST,GET,OPTIONS");
    if (req.method.toLowerCase() == 'options')
        res.send(200);  //让options尝试请求快速结束
    else
        next();
}
--------------------- 
版权声明:本文为CSDN博主「张培跃吧」的原创文章,遵循CC 4.0 by-sa版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/u012149969/article/details/81145144

 

同源:同一主机(host),同一端口(port),同一个协议(protocol)。

跨域的出现原因:浏览器的同源策略。当数据的传输发送过程中出现“源”中的任何一个因素不同时,就出现了跨域问题

解决跨域的常用方法:1.JSONP(SCRIPT标签),2.CORS

工具:nodejsExpress (跨域问题需要同一台电脑上启动两个node项目)

一:nodeJS搭建项目(nunjucks模板引擎):http://www.expressjs.com.cn/starter/generator.html。

二:前端用JQ的ajax请求nodejs后台的接口。

三:编写后台的nodeJS代码。

1.假设准备工作已做好,第一步先实现下同源下的请求实现。

        前端页面下:(5000端口下部署项目)

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{{title}}</title>
<script src="http://libs.baidu.com/jquery/1.11.3/jquery.min.js"></script>
</head>
<body>
    <input type="text" name="" value="" id="name">
    <input type="text" id="id" name="" value="">
    <div class="" id="submit">
        点击
    </div>
        
    <script type="text/javascript">
         $('#submit').on('click',function(){
            var data={
                name:$("#name").val(),
                    id:$("#id").val()
             }
             $.ajax({
                 url:"http://localhost:5000/ajax/deal",
                 type:'post',
                dataType:'json',
                data:data,
                    success:function(data){
                    console.log(data)
                }
             })
         })
         
        
    </script>
</body>
</html>

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值