[英]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.