簡體   English   中英

Node.js 解析查詢字符串

[英]Node.js parsing querystring

我正在學習 Node.js 並嘗試在沒有任何模塊(如 express 或 body-parser)的情況下使表單工作。
我有以下代碼,我希望在 POST 請求時創建一個帶有查詢字符串的 object 並重定向到“聯系成功”頁面,我可以在其中使用來自我的 object 的數據。
我不斷獲得的結果要么是 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 匹配邏輯將不起作用,因為它不考慮查詢字符串。

在開始將/home/等進行匹配之前,您需要將 URL 的查詢字符串和路徑組件從req.url中拆分出來。

因此,對於信息,我使用了以下方法,並且能夠從發布的數據和 console.log 中創建 object:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM