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页面提交数据,服务器就会返回提交的数据。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值