node.JS 创建第一个应用, 本地服务器
创建 node 文档夹, 新建 server.JS 文档
node/server.JS
required 引入 http 模块
- //server.JS
- var http = require("http");
创建服务器
- //server.JS
- var http = require('http');
- http.createServer(function (request, response) {
- // 发送 HTTP 头部
- // 大专栏 node.JS 一 HTTP 状态值: 200 : OK
- // 内容类型: text/plain
- response.writeHead(200, {'Content-Type': 'text/plain'});
- // 发送响应数据 "Hello World"
- response.end('Hello Worldn');
- }).listen(8888);
- // 终端打印如下信息
- console.log('Server running at http://127.0.0.1:8888/');
执行命令, 显示效果
命令提示符
node server.JS
打开浏览器访问 http://127.0.0.1:8888/, 看到一个写着 "Hello World" 的网页
分析 node.JS 的 HTTP 服务器
第一行请求 (require)Node.JS 自带的 http 模块, 并且把它赋值给 http 变量.
接下来我们调用 http 模块提供的函数: createServer . 这个函数会返回 一个对象, 这个对象有一个叫做 listen 的方法, 这个方法有一个数值参数, 指定这个 HTTP 服务器监听的端口号
来源: http://www.bubuko.com/infodetail-3320023.html