Node.js构建 Web 服务( 四 )


Node.js构建 Web 服务

文章插图
 
2. post 方法先来演示如何处理使用post方法来发送请求的表单 。首先,在code/05_webForm目录下执行mkdir post_form命令,并执行以下步骤:
  1. 在code/05_webForm/get_form目录下执行npm install art-template命令,将art-template安装到当前示例项目中 。
  2. 在code/05_webForm/post_form目录下执行touch index.htm,创建一个模版文件,具体如下:
<!DOCTYPE html><html lang="zh-cn"><head><meta charset="UTF-8"><title>个人信息管理</title></head><body><h1>个人信息管理</h1><table><caption>个人数据表</caption><tr><th>姓名</th><th>年龄</th><th>性别</th><th>爱好</th></tr>{{ each db }}<tr><td>{{ $value.name }} </td><td>{{ $value.age }} </td><td>{{ $value.sex }} </td><td>{{ each $value.items }} {{ $value }} {{ /each }}</td></tr>{{ /each }}</table><form action="/add" method="POST"><table><caption>录入新人员</caption><tr><td>姓名:</td><td><input type="text" name="uname" /></td></tr><tr><td>年龄:</td><td><input type="text" name="age"></td></tr><tr><td>性别:</td><td><input type="text" name="sex"></td></tr><tr><td>爱好:</td><td><input type="text" name="items"></td></tr></table><input type="submit" value=https://www.isolves.com/it/wlyx/fwq/2020-08-31/"添加" />3、在code/05_webForm/post_form目录下执行touch app.js,创建一个脚本文件,具体如下:
const http = require('http')const fs = require('fs')const url = require('url')const querystring = require('querystring')const template = require('art-template')class human {constructor(name, age, sex, items=[]){this.name = namethis.age = agethis.sex = sexthis.items = items}}const db = [new human('凌杰', '37', '男', ['看书', '看电影','旅游']),new human('蔓儿', '25', '女', ['看书', '看电影','写作']),new human('张语', '32', '女', ['看书', '旅游','绘画'])]const server = http.createServer(function(req, res){const query = url.parse(req.url, true)if ( query.pathname === '/' ) {fs.readFile('./index.htm', function(err, data) {if ( err !== null ) {return res.end('<h1>404 没找到模版文件!</h1>')}const strHtml = template.render(data.toString(), {"db": db})res.end(strHtml)})}else if ( query.pathname === '/add' ) {req.on('data', function(chunk) {const obj = querystring.parse(chunk.toString())db.push(new human(obj['uname'],obj['age'],obj['sex'],obj['items'].split(','),))})res.writeHead(302, {'location': `/`})res.end()} else {return res.end('<h1>404 页面没找到!</h1>')}})server.listen(8080, function(){console.log('请访问http://localhost:8080/,按Ctrl+C终止服务!')})4、保存所有文件后,在code/05_webForm/post_form目录下执行node app.js命令,结果如下:
Node.js构建 Web 服务

文章插图
 

【Node.js构建 Web 服务】


推荐阅读


上一篇:微服务平台之全链路追踪

下一篇:没有了