本以为用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中总等于零:
取得Node.js提供的数据 取得Node.js提供的数据
没有红字部分或是只有部分,下面两个错误会出现:
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'});
这个细节是从 查到的,在此向作者表示感谢。