如何用node.js创建一个应用

146 阅读1分钟

1. 引入 required 模块

使用require指令来载入http模块,并将实例化的HTTP赋值给变量http。

var http = require("http");

2.创建服务器

使用http.createServer()方法创建服务器,并使用listen方法绑定8888端口。函数通过request,response参数来接收和响应数据。

项目根目录建一个server.js文件。

var http = require('http');
http.createServer(function (request, response) {

    // 发送http头部
    // http 状态值:200:ok
    // 内容类型:text/plain
    response.writeHead(200, {'Content-Type': 'text/plain'});

    // 发送响应数据 “hello world”
    response.end('hello world\n');
}).listen(8888);

// 终端打印如下信息
console.log('Server running at http://127.0.0.1:8888/');

以上代码已完成一个可以工作的HTTP服务器。

打开浏览器访问  http://127.0.0.1:8888/,可看到 “hello world” 的网页。