Node基础学习(十四):Node的简单Web服务器

Node基础学习系列
上一篇:Node基础学习(十三):Node处理请求参数

上一篇博客中,我们学习了Node的处理请求参数的方式,今天我们使用这些知识,搭建一个简单的Web服务,并处理一个GET请求跳转和POST表单提交。

login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登录</title>
</head>
<body>
    <form action="/login" method="post" id="form1">
        <input type="text" name="username" id="username"><br>
        <input type="text" name="password" id="password"><br>
        <input type="submit"  name="submit" id="submit"><br>
    </form>
</body>
</html>

web.js

const http = require('http');
const fs = require('fs');
const querystring = require('querystring');

function doGet(req,res) {
    fs.createReadStream('login.html').pipe(res);
}

function doPost(req,res) {
    res.writeHead(200, {'Content-Type': 'text/plain; charset=utf-8'});
    let body = '';
    req.on('data', function(chunk){
        body += chunk;
    });

    req.on('end', function(){
        body = querystring.parse(body);
        let username = body.username;
        let password = body.password;
        res.end('参数:username:'+username+',password:'+password);
    });
}

const server = http.createServer(function (req,res) {

    if(req.url == '/login') {
        switch (req.method) {
            case 'GET':
                doGet(req, res);
                break;
            case 'POST':
                doPost(req, res);
                break;
            default:
                res.end('other request method');
        }
    }
});

server.listen(8080);

我们运行web.js之后,使用浏览器访问http://localhost:8080/login即可跳转到login.html页面中,然后在login.html页面提交数据,服务器就会返回提交的数据。

猜你喜欢

转载自blog.csdn.net/qq_45193304/article/details/106391302
今日推荐