nodejs进阶(1)—输出hello world

下面将带领大家一步步学习nodejs,知道怎么使用nodejs搭建服务器,响应get/post请求,连接数据库等。

搭建服务器页面输出hello world

 1 var  http  =  require('http');  
 2 http.createServer(function  (request,  response)  {  
 3     response.writeHead(200,  {'Content-Type':  'text/html;  charset=utf-8'});  
 4     if(request.url!=="/favicon.ico"){  //清除第2此访问 node.js bug,第二次访问/favicon.ico
 5         console.log('访问');  
 6         response.write('hello,world 世界');  
 7         response.end();//不写则没有http协议尾
 8     }  
 9 }).listen(8000);  
10 console.log('Server  running  at  http://127.0.0.1:8000/');  
11   
12 /*  
13 启动服务  
14 cmd下执行:  
15 node  1_helloworld.js  
16 浏览器访问:http://localhost:8000  
17 */  

基本语句说明:

1)require 语句,模块通过它加载

对于该语句的解析可参见我的文章《require() 源码解读》(http://www.cnblogs.com/fangsmile/p/6244615.html)

2)http.createServer(function(req, res){  }).listen(8000);

方法说明:

该函数用来创建一个HTTP服务器,并将 requestListener 作为 request 事件的监听函数。最后调用listen函数,监听端口。

接收参数:

requestListener   请求处理函数,自动添加到 request 事件,函数传递两个参数:

    req  请求对象,想知道req有哪些属性,可以查看 “http.request 属性整合”。

    res   响应对象 ,收到请求后要做出的响应。想知道res有哪些属性,可以查看 “http.response属性整合”。

3)response.writeHead(200,  {'Content-Type':  'text/html;  charset=utf-8'});  

方法说明:

向请求的客户端发送响应头。

接收参数:

statusCode   HTTP状态码,如200(请求成功),404(未找到)等。

headers     类似关联数组的对象,表示响应头的每个属性

该函数在一个请求内最多只能调用一次,如果不调用,则会自动生成一个响应头。

4)response.end()

方法说明:

结束响应,告诉客户端所有消息已经发送。当所有要返回的内容发送完毕时,该函数必须被调用一次。

如何不调用该函数,客户端将永远处于等待状态。

将上面的代码复制保存到1_helloworld.js,cmd下执行语句:node  1_helloworld.js 。再去浏览器访问:http://localhost:8000  

下节课介绍函数调用:nodejs进阶2--函数模块调用

原文地址:https://www.cnblogs.com/fangsmile/p/6244788.html