NodeJs获取get/post传值

2020-09-02 16:41:20 浏览数 (1)

代码语言:javascript复制
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

代码语言:javascript复制
<!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>

0 人点赞