• Node.js 本地Xhr取得Node.js服务端数据的例子


    本以为用XHR取Nodejs http出的一段文字很简单,因为xhr取值和nodejs http出文字都是好弄的,谁知一试不是这回事,中间有个关键步骤需要实现。

    nodejs http出文字显示在浏览器很容易,但是头信息是不完整的,下面resp.writeHead一句的红字部分就是这个关键步骤。

    服务器端程序:

    // 内置http模块,提供了http服务器和客户端功能(path模块也是内置模块,而mime是附加模块)
    var http=require("http");
    
    // 创建服务器,创建HTTP服务器要调用http.createServer()函数,它只有一个参数,是个回调函数,服务器每次收到http请求后都会调用这个回调函数。服务器每收到一条http请求,都会用新的request和response对象触发请求函数。
    var server=http.createServer(function(req,resp){
        console.log("请求地址是:"+req.url);
        
       // 这样设置才可以解决跨域的请求,客户端那边才不会被拒绝 resp.writeHead(
    200,{"Content-Type":"text/plain;charset='utf-8'",'Access-Control-Allow-Origin':'*','Access-Control-Allow-Methods':'PUT,POST,GET,DELETE,OPTIONS'});
    resp.write("数据出来"); resp.end();// response对象结束响应 return; }); // 服务器开始运作监听端口 server.listen(3000,"localhost",function(){ console.log("服务器开始运作,监听端口3000中..."); });

    客户端取值就相对简单了,如果上面红字部分没有的话,if(xhr.status>=200 && xhr.status<300) 这个判断是进不去的,因为xhr.status中总等于零:

    <!DOCTYPE html>
    <html lang="utf-8">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <head>
         <title>取得Node.js提供的数据</title>
        </head>
    
         <body onload="run()">
            <h1>取得Node.js提供的数据</h1>
            <div id="msgDiv"></div>
         </body>
    </html>
    <script type="text/javascript">
    <!--
    function run(){
        getNodejsServerData();
    }
    
    function getNodejsServerData(){
        var xhr=new XMLHttpRequest();
        xhr.open("GET","http://localhost:3000",true);
    
        xhr.onreadystatechange=function(){
            console.log("xhr.readyState="+xhr.readyState);
        
            if(xhr.readyState==4){
                console.log("xhr.status="+xhr.status);
    
                if(xhr.status>=200 && xhr.status<300){
                    document.getElementById("msgDiv").innerHTML=xhr.responseText;
                }
            }
        }
    
        xhr.send('');
    }
    
    
    //-->
    </script>

    没有红字部分或是只有部分,下面两个错误会出现:

    XMLHttpRequest cannot load http://localhost:3000/list. The 'Access-Control-Allow-Origin' header has a value 'http://localhost:3000/list' that is not equal to the supplied origin. Origin 'null' is therefore not allowed access.
    
    GET http://localhost:3000/ net::ERR_CONNECTION_REFUSED

    resp.writeHead(200,{"Content-Type":"text/plain;charset='utf-8'",'Access-Control-Allow-Origin':'*','Access-Control-Allow-Methods':'PUT,POST,GET,DELETE,OPTIONS'});

    这个细节是从 http://www.jb51.net/article/96747.htm 查到的,在此向作者表示感谢。

  • 相关阅读:
    关于'for' loop initial declaration used outside C99 mode的说明
    Qt编写安防视频监控系统50-地图配置
    当封装已成为往事
    关于Qt数据库相关开发的一些经验总结
    Qt编写安防视频监控系统49-多数据库支持
    Qt编写安防视频监控系统48-视频参数
    设计测试用例优点和缺点
    常用的七种性能测试方法
    测试资料学习网站推荐
    打印$_SERVER['REQUEST_SCHEME']为空
  • 原文地址:https://www.cnblogs.com/heyang78/p/7526966.html
Copyright © 2020-2023  润新知