Form values from my application is not getting saved in MongoDb - node.js

Being a newbie to Node js and MongoDb, I created a simple form using HTML to get feedbacks. So when I submit my form, I am getting an output that my data is saved, but essential I am not able to see any data in the database. Below is the full code.
HTML:
<form action="/feedback" method="post">
Name <input type = "Name" name=value=""> <br><br>
Roll No <input type = "text" value=""> <br><br>
Meal <input type = "text" value=""> <br><br>
Quality <input type = "text" value=""> <br><br>
Comments <input type = "text" value=""> <br> <br>
<input type = "submit" value ="submit">
</form>
app.js:
const express = require('express');
const bodyParser=require('body-parser')
const mongoose = require('mongoose');
mongoose.Promise=global.Promise;
var app=express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}))
mongoose.connect('mongodb://localhost:27017/feedback');
var feebackschema = new mongoose.Schema({
Name: String,
Rollno: String,
Meal: String,
Quality: String,
Comments: String
});
var feed = mongoose.model('feed',feebackschema);
module.exports=feed
app.get("/", function(req,res){
res.sendFile(__dirname+"/index.html");
})
app.post("/feedback", function(req,res){
var mydata=new feed(req.body);
mydata.save()
.then(item =>{
res.send("Data saved");
})
.catch(err=>{
res.send("Data not saved");
})
})
app.listen(4000, function(){
console.log("Server listening on 4000");
})
EDIT:
HTML
<form action="/feedback" method="post">
Name <input type = "Name" name= "name" value=""> <br><br>
Roll No <input type = "text" name="rollno" value=""> <br><br>
Meal <input type = "text" name="Meal" value=""> <br><br>
Quality <input type = "text" name="quality" value=""> <br><br>
Comments <input type = "text" name="comments" value=""> <br> <br>
<input type = "submit" value ="submit">
</form>

Related

getting this error MongooseError: Operation `contacts.insertOne()` buffering timed out after 10000ms after deploying the application on Heroku

I am working on an application. In which I am using Nodejs, Expressjs and Mongodb(atlas) . Post method is working fine with localhost and Postman but after deploying the application on Heroku getting above error. Please help me , thanks in advance.
This is the image of my folder structure.
folder structure
/src/db/connect.js :
require('dotenv').config();
const mongoose = require('mongoose');
mongoose.connect(process.env.HOST,{useNewUrlParser:true, useUnifiedTopology : true})
.then(() => console.log('connection successful'))
.catch((err) => console.log('Error :' +err));
.env file :
HOST=mongodb+srv://myid:mypassword#cluster0.h6y89rp.mongodb.net/portfolio?retryWrites=true&w=majority
(using my ID and password instead of 'myid:mypassword' in original code )
/src/modals/user.js :
const mongoose = require('mongoose');
const validator = require('validator');
const portfolioSchema = new mongoose.Schema({
name :
{
type : String,
minlength : 3,
maxlength : 50,
required : true,
validate(value)
{
if(validator.isNumeric(value))
{
throw new Error("Name should be alphabatic");
}
}
}, email :
{
type : String,
required : true,
validate(value)
{
if(!validator.isEmail(value))
{
throw new Error('Email not valid');
}
}
},
message : {
type : String
}})
module.exports = new mongoose.model('contact',portfolioSchema);
src/app.js :
require('dotenv').config();
const express = require('express');
const app = express();
require('./db/connect');
const user = require('./modals/user');
const port = process.env.PORT || 5000;
const path = require('path');
const public = path.join(__dirname,'../public');
app.use(express.urlencoded({extended : false}));
app.use(express.json());
app.use(express.static(public));
app.set('view engine','hbs');
app.get('/',(req,res)=>{
res.render('index')//views--> hbs file
})
app.post('/',async(req,res)=>
{
const data = new user(req.body);
try{
const result = await data.save();
res.status(201).send(`your data is added , We will contact you soon have nice day :)`);
}
catch(err)
{
res.status(400).send('Something went wrong'+err);
}
})
app.listen(port,() =>{
console.log('server is started at '+port)
});
Form data is in this file views/index.hbs :
<div class="col-lg-6 col-md-6 col-12">
<form action="/" method="post" class="contact-form webform" role="form">
<div class="form-group d-flex flex-column-reverse">
<input type="text" class="form-control" name="name" id="name" placeholder="Your Name">
<label for="cf-name" class="webform-label">Full Name</label>
</div>
<div class="form-group d-flex flex-column-reverse">
<input type="email" class="form-control" name="email" id="email"
placeholder="Your Email">
<label for="cf-email" class="webform-label">Your Email</label>
</div>
<div class="form-group d-flex flex-column-reverse">
<textarea class="form-control" rows="5" name="message" id="message"
placeholder="Your Message"></textarea>
<label for="cf-message" class="webform-label">Message</label>
</div>
<button type="submit" class="form-control" id="submit-button" name="submit">Send</button>
</form>
</div>
Scripts in package.json file :
"dev" : "nodemon src/app.js -e hbs,js,html",
"start" : "node src/app.js -e hbs,js,html"
both requests are working in postman :
get request in postman
post request in postman
I understood what is wrong with above application.
When we are deploying application on Heroku. We should add our 'mongodb atlas / database url' to heroku which is present in '.env file' env file image . Due to security purpose we are not uploading that file, so we need to make sure we are using the 'mongodb atlas / database url' in Heroku for our database connection .
Here are the steps to add mongodb url in Heroku:
1.Login to Heroku(on browser).
2.click on your application name.
3.Click on settings tab.
Settings tab image
4.Click on Reveal Config Vars.
5.There are two fields 'KEY' and 'VALUE'. In key field add key like in .env file. In this case key will be 'HOST' and in value field add the mongodb url like given in the following image. key value in HEROKU image

The button in express not working for me and have no error codes

I am learning express node.js and trying to run simple calculator code but anytime i press on the button i don't get any response back and also i don't get any errors in my code so i am kind of lost of what i am doin wrong. here is the sample of it so hoping someone can pinpoint me where i am goin wrong will include html code and calculator.js. Thank you in advance.
index.html
<body>
<h1>Calculator</h1>
<form action="/" method="post">
<input type="text" name="num1" placeholder = "first number" value="">
<input type="text" name="num2" placeholder="second number" value="">
<button type="button" name="submit">Calculate</button>
</form>
</body>
calculator.js
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
app.use(bodyParser.urlencoded({extended: true}));
app.get("/", function(req, res){
res.sendFile(__dirname + "/index.html");
});
app.post("/", function(req, res){
var num1 = Number(req.body.num1);
var num2 = Number(req.body.num2);
var result = num1 + num2;
//this line to show result in hyper
console.log(req.body);
res.send("The result is: " + result);
});
app.listen(3000, function(){
console.log("Server running on port 3000");
});
the problem lies in your button type. To submit a form using a button in html, you need to specify the type not as button, but as type.
<form action="/" method="post">
<input type="text" name="num1" placeholder = "first number" value="">
<input type="text" name="num2" placeholder="second number" value="">
<button type="submit" name="submit>Calculate</button>
</form>

Form submit with bootstrap and nodejs

I am using boostrap (via MDB 4) and am trying to get the contact form to work. I have the form presenting as expected. It contains the following button outside the </form> tag
<a class="btn btn-primary" onclick="document.getElementById('contact-form').submit();">Send</a>
The opening line of the form is:
<form id="contact-form" name="contact-form" action="/contact" method="POST">
I am trying to understand how I get the form contents to nodejs and have the following in my Express routes
app.post('/contact', function(req, res){
console.log(req.body.name);
console.log(req.body.email);
console.log(req.body.subject);
console.log(req.body.message);
// code to store here later
});
I know this I am hitting this block as I can console out text from within the route but I get an error every time:
TypeError: Cannot read property 'name' of undefined
All the examples seem to use PHP but I would have thought nodejs would be more than enough for this? I don't have PHP on the box and would rather avoid it if I can stay in nodejs. Anyone got some pointers for me?
It might be worth noting that jquery is used but I don't know if that links in here? The following is at the foot of my html
<script type="text/javascript" src="js/jquery.min.js"></script>
Solved by adding the following to my index.js
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded());
Now when I console.log(req.body); is get:
{
name: 'name',
email: 'name#x.y',
subject: 'test',
message: 'test'
}
I created solution for you:
//connect express
var express = require('express');
var path = require('path');
var ejs = require('ejs');
var partials = require('express-partials');
var app = express();
app.use(express.json());
app.use(partials());
app.use(express.urlencoded({ extended: false }));
app.set('views', path.join(__dirname, '../views'));
app.set('view engine', 'ejs');
//top level routing
app.get('/', (req, res) => {
res.render('index.ejs')
});
app.post('/contact', function(req, res){
res.render('thanks.ejs', {body: req.body})
});
//start server
var http = require('http');
var port = 3000;
app.set('port', port);
var server = http.createServer(app);
server.listen(port);
<!--- start index.ejs -->
<form action="/contact" method="post" class="form-signin">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" name="name" placeholder="Enter name">
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="text" class="form-control" name="email" placeholder="Enter email">
</div>
<div class="form-group">
<label for="name">Subject</label>
<input type="text" class="form-control" name="subject" placeholder="Enter subject">
</div>
<div class="form-group">
<label for="name">Message</label>
<textarea type="text" class="form-control" name="message" placeholder="Enter message"></textarea>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
<!--- end index.ejs -->
<!--- start thanks.ejs--->
<%=JSON.stringify(body)%>
<!--end thanks.ejs --->
<!--- start layout.ejs --->
<html>
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="content">
<%-body -%>
</div>
</div>
</body>
</html>
<!--- end layout.ejs --->
My answer is based on this resource https://exceed-team.com/tech/form-submit-with-bootstrap-and-nodejs

'cannot get addfriend' in express while using postrequest

This is my code app.js code
var express = require("express");
var app = express();
var bp = require("body-parser");
app.use(bp.urlencoded({extended: true}));
var friends = ["babba","lkshjk","kfhkd"];
app.get("/",function(req,res){
res.send("homepage");
});
app.get("/friends",function(req,res){
res.render("friends.ejs",{friends : friends});
});
app.post("/addfriends",function(req,res){
res.send("works fine");
});
var server = app.listen(2700 ,function() {
console.log("started");
});
and this is friends.ejs code
<h1>
friends list
</h1>
<% friends.forEach(function(friend){ %>
<li> <%= friend %> </li>
<% }); %>
<form action="/addfriend?" nature="POST">
<input type="text" ,name="nf" , placeholder="name">
<button>
submit
</button>
</form>
i just need "works fine " in my '/addfriend'
but i am getting
cannot get /addfriend in chrome
this works fine in postman when i try to debug
Your form have to point to the express route.
It should be:
<form action="/addfriends" nature="POST">
<input type="text" ,name="nf" , placeholder="name">
<button>
submit
</button>
</form>
Instead of
<form action="/addfriend?" nature="POST">
<input type="text" ,name="nf" , placeholder="name">
<button>
submit
</button>
</form>
You should declare your route equal you did in express route:
app.post("/addfriends",function(req,res){
res.send("works fine");
});

req.body is always an empty object

I'm doing a React App + Express server,
I want to get in a route /info in my server all the infos from a form in a client,
But when I console log "req.body" in the server, I always get an empty object (see Express code below),
I tried to use body-parser but nothing changes, I don't see where's the issue,
Can somebody help me please ?
React code :
async function getResults(e) {
e.preventDefault();
const info = {
minimumPrice,
maximumPrice
};
console.log("info ", info);
try {
const data = await axios.get("http://localhost:5000/info", info);
console.log("data ", data);
setResults(data.data);
console.log("results ", data.data);
} catch (e) {
console.error(e);
}
}
<form onSubmit={getResults} autoComplete="off" method="get">
<div className="row">
<div className="input-field col s12">
<input
id="minimum-price"
type="number"
name="minimumPrice"
placeholder="Entrez votre prix minimum"
value={minimumPrice}
onChange={e => setMinimumPrice(e.target.value)}
style={{ backgroundColor: "transparent !important" }}
required
/>
<label htmlFor="email">Prix minimum</label>
</div>
</div>
<div className="row">
<div className="input-field col s12">
<input
id="maximum-price"
type="number"
name="maximumPrice"
placeholder="Entrez votre prix maximum"
value={maximumPrice}
onChange={e => setMaximumPrice(e.target.value)}
style={{ backgroundColor: "transparent !important" }}
required
/>
<label htmlFor="email">Prix maximum</label>
</div>
</div>
<div className="row">
<div className="col s12" style={{ textAlign: "center" }}>
<button
className="btn waves-effect waves-light"
type="submit"
name="action"
>
Rechercher
<i className="material-icons right">send</i>
</button>
</div>
</div>
</form>
Express code :
const express = require("express");
const app = express();
const leboncoin = require("leboncoin-api");
const cors = require("cors");
const bodyParser = require("body-parser");
app.use(cors());
app.use(
bodyParser.urlencoded({
extended: true
})
);
app.use(bodyParser.json());
app.get("/info", (req, res) => {
console.log("body ", req.body); <---------- ALWAYS AN EMPTY OBJECT
}
You are making a get request with axios. The parameters sent with get request are available in req.query.
Parameters passed with post request are received in req.body.

Resources