创建Web服务
-
基于 Node.js 环境,使用内置 http 模块,创建 Web 服务程序
-
需求:引入 http 模块,使用相关语法,创建 Web 服务程序,响应返回给请求方一句提示 ‘hello,world’
-
步骤:
- 引入 http 模块,创建 Web 服务对象
- 监听 request 请求事件,对本次请求,做一些响应处理
- 启动 Web 服务监听对应端口号
- 运行本服务在终端进程中,用浏览器发起请求
-
注意:本机的域名叫做 localhost
-
代码如下:
// 1.1 加载 http 模块,创建 Web 服务对象 const http = require('http') const server = http.createServer() // 1.2 监听 request 请求事件,设置响应头和响应体 server.on('request', (req, res) => { // 设置响应头-内容类型-普通文本以及中文编码格式 res.setHeader('Content-Type', 'text/plain;charset=utf-8') // 设置响应体内容,结束本次请求与响应 res.end('欢迎使用 Node.js 和 http 模块创建的 Web 服务') }) // 1.3 配置端口号并启动 Web 服务 server.listen(3000, () => { console.log('Web 服务启动成功了') })
-
在浏览器访问
localhost:3000
就可以获取到服务器响应回来的数据。 -
使用Ctrl+C可以终止服务。
案例-浏览时钟
目标
体验 Web 服务除了接口数据以外,还能返回网页资源等
讲解
-
需求:基于 Web 服务,开发提供网页资源的功能,了解下后端的代码工作过程
-
步骤:
- 基于 http 模块,创建 Web 服务
- 使用 req.url 获取请求资源路径为 /index.html 的时候,读取 index.html 文件内容字符串返回给请求方
- 其他路径,暂时返回不存在的提示
- 运行 Web 服务,用浏览器发起请求
-
代码如下:
const fs = require('fs') const path = require('path') // 1. 基于 http 模块,创建 Web 服务 const http = require('http') const server = http.createServer() server.on('request', (req, res) => { // 2. 使用 req.url 获取请求资源路径,并读取 index.html 里字符串内容返回给请求方 if (req.url === '/index.html') { fs.readFile(path.join(__dirname, 'dist/index.html'), (err, data) => { res.setHeader('Content-Type', 'text/html;charset=utf-8') res.end(data.toString()) }) } else { // 3. 其他路径,暂时返回不存在提示 res.setHeader('Content-Type', 'text/html;charset=utf-8') res.end('你要访问的资源路径不存在') } }) server.listen(8080, () => { console.log('Web 服务启动了') })
注意:端口号切换成了8080