Home > Web Front-end > JS Tutorial > body text

How to implement chat function with nodejs

一个新手
Release: 2017-10-08 09:33:24
Original
1733 people have browsed it

//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=&#39;post&#39; action=&#39;/sendMsg&#39;>    
     昵称:<input type=&#39;text&#39; name=&#39;nickname&#39;><br/>    
     您说:<input type=&#39;text&#39; name=&#39;msg&#39;>    
     <input type=&#39;submit&#39; name=&#39;&#39; value=&#39;发送&#39;>    
     </form>    
     </body>    
     </html>    
//这是app.js的代码
&#39;use strict&#39;;
const express = require(&#39;express&#39;);
const app = express();
const router = express.Router();
const bodyParser = require(&#39;body-parser&#39;);//消息列表
let msgs = [{    
    nickname:&#39;pxzj.cn&#39;,msg:&#39;pxzj一个神奇的网站&#39;},{    
    nickname:&#39;淘宝&#39;,msg:&#39;我才是中国互联网老大&#39;}];//注册一个引擎html后缀的处理
    app.engine(&#39;html&#39;,require(&#39;express-art-template&#39;));//给art-template设置 debug:trueapp.set(&#39;view options&#39;,{    
    debug:true});router.get(&#39;/&#39;,(req,res)=>{    
    res.render(&#39;index.html&#39;,{        
    msgs:msgs   //可以简写 msgs    });//找views目录})
    .post(&#39;/sendMsg&#39;,(req,res)=>{    //接收数据    
    let formObj = req.body;    
    let nickname = formObj.nickname;   
    let msg = formObj.msg;    //加入到数组中    
    msgs.push({        
    nickname,msg    });    //响应首页    
    res.render(&#39;index.html&#39;,{        
    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);
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!