1. 程式人生 > >使用Node.js建立一個簡單的HTTP伺服器

使用Node.js建立一個簡單的HTTP伺服器

1.建立一個名為test.js的檔案,內容為:

// test.js
// 請求http模組
var http = require('http');

// 建立伺服器
http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write("<h1>Node.js</h1>");
    res.end('<p>Hello World</p>');
}).listen(3000);

// 控制檯列印
console.log("start...");
console.log("HTTP server is listening at port 3000...");

2.在命令列工具中開啟test.js所在的資料夾,然後輸入:

node test

3.在瀏覽器中輸入:

http://127.0.0.1:3000/

4.即可看到瀏覽器中顯示:

至此,用Node.js建立的一個簡單伺服器就完成了。