NodeJs获取get/post传值

时间:2022-07-24
本文章向大家介绍NodeJs获取get/post传值,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
const http = require('http');
const routes = require('./module/routes')
const url = require('url')
const ejs = require('ejs')
http.createServer((req, res) => {
    routes.static(req, res, './static')
    // 路由
    let pathname = url.parse(req.url).pathname;
    // 获取请求类型
    console.log(req.method)
    if (pathname == '/news') {
        // 获取GET传值
        // url:http://127.0.0.1:8081/news?id=1
        var query = url.parse(req.url, true).query;
        console.log(query.id)
        res.writeHead(200, {
            'Content-Type': 'text/html;charset="utf-8"'
        });
        res.end('GET传值获取成功')
    } else if (pathname == '/login') {
        // POST表单传值
        ejs.renderFile('./views/form.ejs', {}, (err, data) => {
            res.writeHead(200, {
                'Content-Type': 'text/html;charset="utf-8"'
            });
            res.end(data)
        })
    } else if (pathname == '/doLogin') {
        // 获取POST传值
        let postData = ""
        req.on('data', (chuck) => {
            postData += chuck
        })
        req.on('end', () => {
            res.end(postData)
        })
    }
}).listen(8081);

form.ejs

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <form action="/doLogin" method="POST">
        <input type="text" name="username" value="admin" />
        <input type="password" name="password" value="123456" />
        <input type="submit" value="提交">
    </form>
</body>

</html>