Node.js 正在解析查询字符串

Node.js parsing querystring

我正在学习 Node.js 并尝试在没有 任何模块(例如 express 或 body-parser)的情况下制作一个表单。
我有以下代码,我想根据 POST 请求创建一个包含查询字符串的对象,并重定向到“联系成功”页面,我可以在其中使用我的对象中的数据。
我不断获得的结果是 404 错误,因为我被带到带有查询字符串的 URL 或只是 firefox 加载“永远” 关于如何让它工作的任何建议? :)

//we need http to be able to process http requests
const http = require('http')
// we need fs because each http request will ba handled by creating a readstream and piping it to response
// fs will read the file to be piped
const fs = require('fs')
const qs = require('querystring')

const server = http.createServer(function(req, res){
    console.log('Request was made at ' + req.url)
    if(req.url === '/' || req.url === '/home'){
        // home page
        res.writeHead(200, {'Content-type': 'text/html'})
        fs.createReadStream(__dirname + '/html_files/index.html').pipe(res)
    } else if(req.url === '/contact'){
        if (req.method === 'POST'){
            //handling the POST request only IF the request is made
            const body =''
            req.on('data', function(data){
                body += data
            })
            req.on('end', function(){
                const post = querystring.parse(body)
                console.log(post)
                res.writeHead(200, {'Content-type': 'text/html'})
                fs.createReadStream(__dirname + '/html_files/contact-success.html').pipe(res)
            })
        } else {
            res.writeHead(200, {'Content-type': 'text/html'})
            fs.createReadStream(__dirname + '/html_files/contact.html').pipe(res)
        }
    } else if(req.url === '/contact-success'){
        // page to be displayed once the form is submited with POST request
        res.writeHead(200, {'Content-type': 'text/html'})
        fs.createReadStream(__dirname + '/html_files/contact-success.html').pipe(res)
    }
})

// configuring the port and address of the localhost
// I chose 3000 here because another app is on 8000 and sometimes the cache does weird stuff
server.listen(3000, '127.0.0.1')
// just quick console feedback that we're connected on the right port
console.log('Now listening to port 3000')

查询字符串是 URL 的一部分,因此您的 URL 匹配逻辑将不起作用,因为它不考虑查询字符串。

您需要在 开始匹配 URL 之前,将 URL 的查询字符串和路径组件从 req.url 中拆分出来//home

因此,为了获得信息,我使用了以下方法并能够从发布的数据创建一个对象,console.log 它:

if(req.method === 'POST'){
            // we state that body is empty
            let body = ''
            // on event 'data' a chunk of data is sent to body and stringified
            req.on('data', chunk => {
                body += chunk.toString()
                //on the end of stream, we parse the body and console,log it
                req.on('end', () => {
                    console.log(parse(body))
                })
            })
            // trying to redirect to contact-successafter posting
            res.writeHead(200, {'Content-type': 'text/html'})
            fs.createReadStream(__dirname + '/html_files/contact-success.html').pipe(res)