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、運行結果

這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章