美文网首页Node.js
Node.js处理get,post请求

Node.js处理get,post请求

作者: 我就是要学习 | 来源:发表于2020-02-17 10:59 被阅读0次

    服务端代码

    const http = require('http')
    const fs = require('fs')
    const url = require('url')
    const querystring = require('querystring')
    
    const server = http.createServer((req, res) => {
        let str = ''
        console.log(req.url, req.method);
        let { pathname, query } = url.parse(req.url, true)
    
        switch (pathname) {
            case '/login':
                req.on('data', data => {
    
                    //不推荐 以后会有其他方式
                    str += data
                })
    
                req.on('end', () => {
                    console.log(str);
                    // console.log(querystring.parse(str));
                    let { name, password } = querystring.parse(str)
                    res.write(`name:${name} password:${password}  success`)
                    res.end()
                })
                break
    
            case '/sum':
                console.log(query);
                let { a, b } = query
                res.write(`${a}+${b}=2333`)
                res.end()
                break
    
    
            default:
                fs.readFile('www/home.html', (err, data) => {
                    if (err) {
                        res.writeHead(404)
                        res.write('404 Not Found')
                    } else {
                        res.write(data)
                    }
                    res.end()
                })
        }
    })
    
    server.listen(8080, () => {
        console.log('http://localhost:8080/');
    })
    

    目录结构

    image.png

    HTML代码

    <body>
        <form target="_blank" action="http://localhost:8080/login" method="POST">
            <input type="text" name="name">
            <input type="password" name="password">
            <input type="submit" value="登录">
        </form>
        <br>
        <form target="_blank" action="http://localhost:8080/sum" method="GET">
            <input type="text" name="a">
            <input type="text" name="b">
            <input type="submit" value="求和">
        </form>
    </body>
    
    image.png

    相关文章

      网友评论

        本文标题:Node.js处理get,post请求

        本文链接:https://www.haomeiwen.com/subject/rphpfhtx.html