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 查到的,在此向作者表示感谢。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值