话不多说直接上代码,
具体代码如下:
var http = require('http');
http.createServer(function(request,response){
response.writeHead(200,{'Content-Type': 'text/plain'});
response.end(request.url+"\nHello world");
}).listen(1234,'127.0.0.1');
console.log('Server running at');
运行这段代码,在浏览器中打开http://localhost:1234或http:// 127.0.0.1:1234,页面显示 Hello world字样,
表明一个简单的http服务器就创建成功了。
下面对代码进行解析:
var http = require('http'); 为引用 http 模块
http.createServer()为创建服务器对象
function(request,response){
response.writeHead(200,{'Content-Type': 'text/plain'});
response.end(request.url+"\nHello world");
} 为回调函数
.listen(1234,'127.0.0.1'); 为监听端口1234, 只许本地访问。