HTTP服务器

    要开发HTTP服务器程序,从头处理TCP连接,解析HTTP是不现实的。这些工作实际上已经由Node.js自带的 http 模块完成了。应用程序并不直接和HTTP协议打交道,而是操作 http 模块提供的 request response 对象。

    request 对象封装了HTTP请求,我们调用 request 对象的属性和方法就可以拿到所有HTTP请求的信息;

    response 对象封装了HTTP响应,我们操作 response 对象的方法,就可以把HTTP响应返回给浏览器。

    用Node.js实现一个HTTP服务器程序非常简单。我们来实现一个最简单的Web程序 hello.js ,它对于所有请求,都返回 Hello world!

    'use strict';



    // 导入http模块:

    var http = require('http');



    // 创建http server,并传入回调函数:

    var server = http.createServer(function (request, response) {

    // 回调函数接收request和response对象,

    // 获得HTTP请求的method和url:

    console.log(request.method + ': ' + request.url);

    // 将HTTP响应200写入response, 同时设置Content-Type: text/html:

    response.writeHead(200, {'Content-Type': 'text/html'});

    // 将HTTP响应的HTML内容写入response:

    response.end('<h1>Hello world!</h1>');

    });



    // 让服务器监听8080端口:

    server.listen(8080);



    console.log('Server is running at http://127.0.0.1:8080/&#39;);

    在命令提示符下运行该程序,可以看到以下输出:

    $ node hello.js

    Server is running at http://127.0.0.1:8080/

    不要关闭命令提示符,直接打开浏览器输入 http://localhost:8080 ,即可看到服务器响应的内容:

    HTTP服务器 - 图1

    同时,在命令提示符窗口,可以看到程序打印的请求信息:

    GET: /

    GET: /favicon.ico

    这就是我们编写的第一个HTTP服务器程序!