zoukankan      html  css  js  c++  java
  • 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服务器。

  • 相关阅读:
    vs2010使用刚刚配置好的STLport提示检测到"_MSC_VER”的不
    UltraISO制作Linux启动盘
    RedHat 简易配置 VNC Server 与VNC View详细说明!
    数据库中树状关系(各种树状分类)的查找
    java–jsp & javabean
    linux 下android的一键root
    MySQL简明教程及表设计原则
    Activity 生存周期
    java web EL表达式
    ubuntu下调试android手机,并进入手机shell终端
  • 原文地址:https://www.cnblogs.com/zhoudaozhang/p/4704396.html
Copyright © 2011-2022 走看看