http(二)

1.将表格中的数据动态加入表格中,js脚本中拼接了css,html,script,练习

const http = require("http");
const urlTool = require("url");  //1,浏览器向node服务发送了一个请求,返回了一个表格的html  //2.然后在想浏览器发送一个css.java的请求,返回css,  //3.浏览器对不标准的html也会解析 3 

const server = http.createServer((request, response)=>{
    //获取参数
    let method = request.method.toUpperCase();
    let pathname = urlTool.parse(request.url).pathname;
    //检测路径
    if(method === ‘GET‘ && pathname === ‘/users‘){  //如果报文路径和文件路径没关联,可以自定义url
        //1. 乱码问题
        response.setHeader("content-type",‘text/html;charset=utf-8‘);
        const arr = [
            {name: ‘knight‘, age: 18},
            {name: ‘xiaoming‘, age: 20},
            {name: ‘xiaoning‘, age: 28},
            {name: ‘xiaotian‘, age: 18},
            {name: ‘xiaohigh‘, age: 20},
        ];
        //返回一个表格
        let str = `
        <link rel="stylesheet" href="/css.java">
        <script src="/app.js"></script>
        <table border="1"><tr><td>姓名</td> <td>年龄</td></tr>`;
        for(let i=0;i<arr.length;i++){
            str += `<tr><td>${arr[i].name}</td><td>${arr[i].age}</td></tr>`;
        }
        str += `</table>`;
        
        response.end(str);
    }else if(method === ‘GET‘ && pathname === ‘/css.java‘){
        response.end(`
            body{
                background:pink;
            }
        `);
    }else{
        response.end("OK");
    }
});

server.listen(8000, ()=>{
    console.log(‘server is running..  8000 端口监听......‘);
})

二,登录表单,服务响应练习

表单

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>登录</title>
    <link href="https://cdn.bootcss.com/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>

<body>
    <div class="container">
        <div class="col-xs-4 col-xs-offset-4">
            <h2 class="page-header">用户登录</h2>
            <form method="POST" action="/login">
                <div class="form-group">
                    <label for="exampleInputEmail1">用户名</label>
                    <input type="text" class="form-control" name="username">
                </div>
                <div class="form-group">
                    <label for="exampleInputPassword1">密码</label>
                    <input type="password" class="form-control" name="password">
                </div>
                <hr>
                <button type="submit" class="btn btn-primary btn-block">登录</button>
            </form>
        </div>
    </div>
</body>

</html>

js脚本

const http = require(‘http‘);
const urlTool = require("url");
const fs = require(‘fs‘);
const qs = require(‘querystring‘);
//1.浏览器想发送一个get,/login的请求,然后node服务器返回一个login.html(一个表单)给浏览器
// 2.然后浏览器将表单内容填写了,发送了post,/login的请求,服务器返回了请求体的数据


// function getClientIp(req) {
//     return req.headers[‘x-forwarded-for‘] || // 判断是否有反向代理 IP
//         req.connection.remoteAddress || // 判断 connection 的远程 IP
//         req.socket.remoteAddress || // 判断后端的 socket 的 IP
//         req.connection.socket.remoteAddress;
// }


const server = http.createServer((request, response) => {
    //获取 方法和路径
    let method = request.method.toUpperCase();
    let pathname = urlTool.parse(request.url).pathname;
    //如果 GET /login 则返回一个表单页面
    if (method === ‘GET‘ && pathname === ‘/login‘) {
        fs.readFile(__dirname + ‘/login.html‘, (err, data) => {
            response.end(data);
        });
        // POST /login 处理表单的数据
    } else if (method === ‘POST‘ && pathname === ‘/login‘) {
        //请求体数据提取
        //1. 声明变量
        let body = ‘‘;
        //2. 绑定 data 事件
        request.on(‘data‘, chunk => {
            body += chunk;
        })
        //3. 绑定 end 事件
        request.on(‘end‘, () => {
            console.log(body);
            //将请求体的字符串形式 转为对象形式
            let data = qs.parse(body);
            // fs.writeFile("./access.log", body + ‘--ip:‘+ getClientIp(request)+‘\r\n‘, (err) => {
            //     console.log(data);
            //     response.end(body);
            // })

            console.log(data);
            response.end(body);

        })
    }else {
        response.end("404");
    }
});

server.listen(80, () => {
    console.log("服务已经启动, 80 端口监听中....");
})

相关推荐