I am learning Node.js and try to make a form work without any module like express or body-parser.
I have the below code and I want upon POST request to create an object with the query string and redirect to a "contact-success" page where I could use the data from my object.
The results I keep obtaining is either a 404 error because I am taken to a URL with query string or just firefox loading "forever"
Any advice on how to have it work? :)
//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')
console.log(body)beforeconst post = querystring.parse(body)? The body is definetely not a query string it's most probablymultipart/form-data. You also probably don't understand the difference between body and query string. They are two different thing. The query string has a specific format and is part if the url whereas body of the request can be anything and has nothing to do with url address.