最简单的代码
var http = require('http');
const server=http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
})
server.listen(1337, "127.0.0.1");
console.log('Server running at http://127.0.0.1:1337/');保存为test.js,在控制台中输入:node test.js,显示如下:
在浏览器中输入http://127.0.0.1:1337/ ,可以看到网页中的hello world
代码说明:
a. 全局方法require()是用来导入模块的,一般直接把 require() 方法的返回值赋值给一个变量,在 JavaScript 代码中直接使用此变量即可 。require("http") 就是加载系统预置的 http 模块
b. http.createServer 是模块的方法,目的就是创建并返回一个新的web server对象,并且给服务绑定一个回调,用以处理请求。
c. 通过 http.listen() 方法就可以让该 HTTP 服务器在特定端口监听。
d. console.log控制台中输入内容。
代码参考,非常感谢:
http://www.cnblogs.com/Darren_code/archive/2011/10/31/2207063.html