In my below app, connected to mongodb I have created a post request to manage the form I have in my html file.
The posting goes well when it comes to console.log and I clearly see the object being created. My issue is that it writes only "email address" in mongodb and I would like to have the "name" and "department".
Please note that I am not using express on purpose, this is an assesment I am doing for learning pruposes
app.js:
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 mongoose = require('mongoose')
const { parse } = require('querystring')
const { request } = require('http')
// connect to DB
mongoose.connect('mongodb+srv://baptiste:Tractor5@cluster0.myfpj.mongodb.net/DB-Test-made-contact?retryWrites=true&w=majority', {useMongoClient: true})
// checking if DB is properly connected
const db = mongoose.connection
db.on('error', console.error.bind(console, 'connection error'))
db.once('open', function(){
console.log('db connected')
})
// schema for DB - like a blueprint of everything that will be saved in it
const madeContactSchema = new mongoose.Schema({
name: String,
dept: String,
email: String
})
const MadeContact = mongoose.model('MadeContact', madeContactSchema)
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'){
// create a if statement to manage the post request (not sure about this part but let's try)
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))
// create a const in order to allow us to post into mongodb
const newMadeContact = MadeContact(parse(body)).save(function(err){
if (err) throw err
console.log('Item saved')
})
})
// trying to redirect to contact-successafter posting
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)
console.log(madeContact)
} else {
res.writeHead(200, {'Content-type': 'text/html'})
fs.createReadStream(__dirname + '/html_files/404.html')
}
})
// 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 a quick console feedback that we're conencted on the right port
console.log('Now listening to port 3000')
contact.html:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<nav>
<p><a href="/">Home page</a></p>
<p><a href="/contact">Contact</a></p>
</nav>
<h1>Contact me!</h1>
<p>Let's get in touch!</p>
<form action="/contact" method="POST">
<label for="name">Who do you want to contact?</label><br>
<input type="text" id="name" name="name"><br>
<label for="dept">Which Department?</label><br>
<input type="text" id="dept" name="department"><br>
<label for="email">Your email address:</label><br>
<input type="email" id="email" name="email"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Thanks in advance for any tips:)
I tried also to write as follows and did not write anything:
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))
// create a const in order to allow us to post into mongodb
const newMadeContact = MadeContact({
name: body.name,
dept: body.dept,
email: body.email
}).save(function(err){
if (err) throw err
console.log('Item saved')
})
})
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))
// create a const in order to allow us to post into mongodb
const result=parse(body);
const newMadeContact = MadeContact({
name: result.name,
dept: result.department, //check your form input field
email: body.email
}).save(function(err){
if (err) throw err
console.log('Item saved')
})
})
first i have parsed the body and assigned to constant (result) then the other change is result.department because you have named department as input filed in forms
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.