前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >NodeJs获取get/post传值

NodeJs获取get/post传值

作者头像
明知山
发布2020-09-02 16:41:20
1.2K0
发布2020-09-02 16:41:20
举报
文章被收录于专栏:前端开发随笔前端开发随笔
代码语言: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>
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020-05-17 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档