使用nodejs搭建http服务很简单,代码如下:
var http = require("http");//获取http对象 http.createServer( //匿名的回调函数,当有请求进来的时候调用该函数 //req参数相当于J2EE的HttpServletRequest, //res参数相当于J2EE的HttpServletResponse function(req,res){ console.log("run ... "); res.writeHead(200,{'Content-Type':'text/html'});//响应代码为200(正常) 已html方式展示 res.write("<h1>Hello World</h3>"); //输出html代码 res.end('<p>hello World</p>');//输出html代码,必须要调用res.end()方法,否则浏览器一直等待直到该方法调用 } ).listen(3000); //监听3000端口 console.log(" HTTP Server is Listening at port 3000.");
打开浏览器输入http://127.0.0.1:3000/后回车即可看到界面
接下来对上面的代码进行改造:
var http = require("http");//获取http对象 var fs = require("fs"); //获取fs对象 http.createServer( //匿名的回调函数,当有请求进来的时候调用该函数 //req参数相当于J2EE的HttpServletRequest, //res参数相当于J2EE的HttpServletResponse function(req,res){ console.log("run ... "); res.writeHead(200,{'Content-Type':'text/html'});//响应代码为200(正常) 已html方式展示 //异步读取数据 fs.readFile("app02.html","utf-8",function(err,data){ if(err){//如果出现错误则直接显示错误原因 res.end(err); }else{//如果成功读取文件则返回文件内容 res.end(data.toString()); } }); } ).listen(3000); //监听3000端口 console.log(" HTTP Server is Listening at port 3000.");
打开浏览器输入http://127.0.0.1:3000/后回车即可看到界面