【发布时间】:2020-07-03 10:32:16
【问题描述】:
我正在学习 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')
【问题讨论】:
-
您在
const post = querystring.parse(body)之前尝试过console.log(body)吗?正文绝对不是查询字符串,它很可能是multipart/form-data。您也可能不了解正文和查询字符串之间的区别。他们是两个不同的东西。查询字符串具有特定的格式,如果是 url,则它是一部分,而请求的正文可以是任何内容,与 url 地址无关。 -
我会朝那个方向看,谢谢!
标签: javascript node.js post query-string