Node.js尝鲜——留言功能

1、新建一个文件,使用下面的代码新建创建一个05.js文件,下面的代码就是创建一个http服务器,然后监听8000端口。

在服务器中,首先分析请求的路径,然后根据路径进行相应的操作,然后返回相应的数据。

const http = require('http');
const url = require('url');
const qs = require('querystring');

var form = 
'<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Document</title></head><body><form action="/liuyanok" method="post"><p>内容:<input type="text" name="msg"></p><p><input type="submit" value="提交"></p></form></body></html>';

http.createServer((req,res)=>{
    var path = url.parse(req.url).path;//获取请求路径
    var body = '';//post实体数据
    res.writeHead(200,{"Content-type":"text/html;charset=utf-8"});
    if(path == '/'){//根路径
        res.write("<h1>Hello Node.js</h1>");
        res.end();
    }else if(path == '/liuyan'){//留言路径
        res.write(form);
        res.end();
    }else if(path == '/liuyanok'){//留言post路径
        req.on('data',(chunk)=>{
            body += chunk;
        });
        req.on('end',()=>{
            console.log(qs.parse(body));//把留言数据打印到控制台
        });
        res.end('谢谢你');
    }
}).listen(8000);

2、使用命令开启http服务器

node 05.js

这里写图片描述

3、运行结果

这里写图片描述

原文地址:https://www.cnblogs.com/cnsec/p/13407008.html