摘要:Node.js http出文字显示在浏览器很容易,但是头信息是不完整的,本文讲解了一个Node.js 本地Xhr取得Node.js服务端数据开发实例,希望对大家有所帮助。
nodejs http出文字显示在浏览器很容易,但是头信息是不完整的,下面resp.writeHead一句的“Access-Control-Allow-Origin':'*','Access-Control-Allow-Methods':'PUT,POST,GET,DELETE,OPTIONS'});
resp.write("数据出来");”就是这个关键步骤。
服务器端程序:
// 内置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","//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 //localhost:3000/list. The 'Access-Control-Allow-Origin' header has a value '//localhost:3000/list' that is not equal to the supplied origin. Origin 'null' is therefore not allowed access. GET //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'});
本文由职坐标整理发布,更多相关知识,请关注职坐标WEB前端Node.js频道!
您输入的评论内容中包含违禁敏感词
我知道了
请输入正确的手机号码
请输入正确的验证码
您今天的短信下发次数太多了,明天再试试吧!
我们会在第一时间安排职业规划师联系您!
您也可以联系我们的职业规划师咨询:
版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
沪公网安备 31011502005948号