创建文件server.js
//es5 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 node World\n‘); }).listen(3000); // 终端打印如下信息 console.log(‘Server running at http://127.0.0.1:3000/‘);
//es6 const http = require(‘http‘); const hostname = ‘127.0.0.1‘; const port = 3000; const server = http.createServer((req, res) => { res.statusCode = 200; res.setHeader(‘Content-Type‘, ‘text/plain‘); res.end(‘Hello World\n‘); }); server.listen(port, hostname, () => { console.log(`Server running at http://${hostname}:${port}/`); });
运行
~:node server.js
打开浏览器输入url:127.0.0.1:3000
测试是否运行成功!