http接收页面传递的数据

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title></title>
 6 </head>
 7 <body>
 8 <form action="http://localhost:3000/" method="post">
 9     <label>用户名: <input type="text" name="user"></label><br>
10     <label>密  码: <input type="password" name="pwd"></label><br>
11     <input type="submit" value="提交">
12 </form>
13 </body>
14 </html>
 1 const http = require('http');
 2 const queryString = require('querystring');
 3 const util = require('util');
 4 
 5 http.createServer((req, res)=>{
 6     let postData;
 7     // post请求, 得做事件监听
 8     req.on('data', (data)=>{
 9         postData += data;
10     });
11 
12     // 监听数据接收完毕
13     req.on('end', ()=>{
14        postData = queryString.parse(postData);
15         console.log(util.inspect(postData));
16         res.end('数据接收成功!');
17     });
18 
19 }).listen(3000, '127.0.0.1');
 1 const http = require('http');
 2 const url = require('url');
 3 const fs = require('fs');
 4 const path = require('path');
 5 
 6 // 创建服务器
 7 http.createServer((req, res) => {
 8     // 1. 获取url的路径
 9     let pathUrl = url.parse(req.url);
10     let pathName = pathUrl.pathname;
11     console.log(pathName);
12 
13     // 2. 判断
14     if ('/like' === pathName) {
15         fs.readFile(path.join(__dirname, 'page/page1.html'), (err, data)=>{
16             if(err) throw err;
17             res.writeHead(200, {'content-type': 'text/html;charset=utf-8'});
18             res.end(data);
19         });
20     }else if('/page2' === pathName){
21         fs.readFile(path.join(__dirname, 'page/page2.html'), (err, data)=>{
22             if(err) throw err;
23             res.writeHead(200, {'content-type': 'text/html;charset=utf-8'});
24             res.end(data);
25         });
26     }else if('/css' === pathName){
27         fs.readFile(path.join(__dirname, 'page/index.css'), (err, data)=>{
28             if(err) throw err;
29             res.writeHead(200, {'content-type': 'text/css;charset=utf-8'});
30             res.end(data);
31         });
32     }else if('/img' === pathName){
33         fs.readFile(path.join(__dirname, 'page/img2.jpg'), (err, data)=>{
34             if(err) throw err;
35             res.writeHead(200, {'content-type': 'image/jpg'});
36             res.end(data);
37         });
38     }else {
39         res.writeHead(404, {'content-type': 'text/html;charset=utf-8'});
40         res.end('<h1>404, 当前的页面不存在!</h1>');
41     }
42 }).listen(3000);

 

posted @ 2019-06-30 23:57  疏影横斜水清浅  阅读(928)  评论(0编辑  收藏  举报