//html代码 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> 正在热聊中:<br/> <ul> {{each msgs}} <li>{{$value.nickname}}:{{$value.msg}}</li> {{/each}} </ul> <form method='post' action='/sendMsg'> 昵称:<input type='text' name='nickname'><br/> 您说:<input type='text' name='msg'> <input type='submit' name='' value='发送'> </form> </body> </html> //这是app.js的代码 'use strict'; const express = require('express'); const app = express(); const router = express.Router(); const bodyParser = require('body-parser');//消息列表 let msgs = [{ nickname:'pxzj.cn',msg:'pxzj一个神奇的网站'},{ nickname:'淘宝',msg:'我才是中国互联网老大'}];//注册一个引擎html后缀的处理 app.engine('html',require('express-art-template'));//给art-template设置 debug:trueapp.set('view options',{ debug:true});router.get('/',(req,res)=>{ res.render('index.html',{ msgs:msgs //可以简写 msgs });//找views目录}) .post('/sendMsg',(req,res)=>{ //接收数据 let formObj = req.body; let nickname = formObj.nickname; let msg = formObj.msg; //加入到数组中 msgs.push({ nickname,msg }); //响应首页 res.render('index.html',{ msgs:msgs });})// parse application/x-www-form-urlencodedapp.use(bodyParser.urlencoded({ extended: false }));// parse application/jsonapp.use(bodyParser.json());//以上两个中间件为的是先挂载属性,再执行router路由 req.bodyapp.use(router);app.listen(8888);
The above is the detailed content of How to implement chat function with nodejs. For more information, please follow other related articles on the PHP Chinese website!