why my form data doesn't stored in database? - javascript

My app.js entire codes:
var express = require("express");
var app = express();
var port = 3000;
app.listen(port, () => {
console.log("Server listening on port " + port);
});
var mongoose = require("mongoose");
mongoose.Promise = global.Promise;
mongoose.connect("mongodb://localhost:27017/node-demo", { useNewUrlParser: true, useUnifiedTopology: true });
app.use("/", (req, res) => {
res.sendFile(__dirname + "/index.html");
});
var nameSchema = new mongoose.Schema({
firstName: String,
lastName: String
});
var User = mongoose.model("User", nameSchema);
app.post("/addname", (req, res) => {
});
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post("/addname", (req, res) => {
app.post("/addname", (req, res) => {
var myData = new User(req.body.firstName, req.body.lastName);
myData.save()
.then(item => {
res.send("item saved to database");
})
.catch(err => {
res.status(400).send("unable to save to database");
});
})
});
This is my index.html file
<!DOCTYPE html>
<html>
<head>
<title>Intro to Node and MongoDB
</title>
</head>
<body>
<h1>Into to Node and MongoDB</h1>
<form method="post" action="/addname">
<label>Enter Your Name</label><br>
<input type="text" name="firstName" placeholder="Enter first name..." required>
<input type="text" name="lastName" placeholder="Enter last name..." required>
<input type="submit" value="Add Name">
</form>
</body>
<html>
After writing my code I open my mongod server than start mongo in other terminal then I run my app.js it worked properly it create server localhost:3000 then I went to my host I add my name in form and then submit, but it doesn't add to my database
Why this is not working?
My form data doesn't stored in my mongodb database. Please help me!

I think the body-parser library is deprecated on express 4 and later versions.
please use
app.use(express.json())
instead of body=parser.
not need to call any npm packages for parsing data from the form.

Here is the issue:
var myData = new User(req.body.firstName, req.body.lastName);
you have to pass an object to new User
var myData = new User( { firstName:req.body.firstName, lastName:req.body.lastName } );

i think i know what is wrong.
change app.use("/"... to app.get("/"...
bacause use handles all requests including POST. so when you send any request it sends the html file again and kills any other process.
app.get("/", (req, res) => {
res.sendFile(__dirname + "/index.html");
});

I think you are not passing data correctly in the user model.
app.post("/addname", (req, res) => {
// make sure your request object is getting the same properties
var myData = new User(req.body.firstName, req.body.lastName);
myData.save()
.then(item => {
res.send("item saved to database");
})
.catch(err => {
res.status(400).send("unable to save to database");
});
});
As you updated the code for form, lastName is the fieldName. You should make the changes in the schema object too.
Also, Please check the request headers that comes in if it is of Accept:multipart/form-data then the bodyParser won't work instead you should use multer.
Some useful body parsers that you might need to consider if needed.
form-data: multer
x-www-form-urlencoded: express.urlencoded()
raw: express.raw()
json: express.json()
text: express.text()
Updated app.js file:
var express = require("express");
var app = express();
var port = 3000;
app.listen(port, () => {
console.log("Server listening on port " + port);
});
var mongoose = require("mongoose");
mongoose.Promise = global.Promise;
mongoose.connect("mongodb://localhost:27017/node-demo", { useNewUrlParser: true, useUnifiedTopology: true });
app.use("/", (req, res) => {
res.sendFile(__dirname + "/index.html");
});
var nameSchema = new mongoose.Schema({
firstName: String,
lastName: String
});
var User = mongoose.model("User", nameSchema);
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post("/addname", (req, res) => {
var myData = new User(req.body.firstName, req.body.lastName);
myData.save()
.then(item => {
res.send("item saved to database");
})
.catch(err => {
res.status(400).send("unable to save to database");
});
});
Note: you have added two extra routes with same route handler, I have just removed it. Update this file in your project and run it.

Related

How to send data from a form to mongodb?

I am created a nodejs project the structure of py project is:
api.js is:
const express = require('express');
const router = express.Router();
const add = require('../model/myModel');
router.get('/',function(req,res){
res.render('myForm');
});
router.post('/add', (req, res) => {
console.log(req.body)
n = req.body.name,
phone = req.body.phone,
console.log(`name = ${n}`)
let obj = new Address({
name: n,
phone: phone,
});
// add this instance to the database.
obj.save()
.then((address) => {
res.send(address);
})
.catch((err) => {
console.log(error);
});
});
module.exports = router;
and my app.js is:
const express = require('express');
const mongoose = require('mongoose');
const route = require('./route/api');
//Initialize express app
const app = express();
// Connecting to DB
const dbPath = 'mongodb://localhost:27017/testdb';
const dbOptions = {useNewUrlParser: true};
mongoose.connect(dbPath, dbOptions).then(()=>{
console.log(`We are connected to our database ${dbPath}`);
}).catch((error)=>{
console.log(`We are note able to connect to our database: ${error}`);
});
app.use(express.static('public'));
app.use(express.json());
app.set("view engine", "ejs");
// initialize routes
app.use("/api", route);
//Initialize the sever
app.listen(3000, () => {
console.log('sever listening on port:3000');
});
and myForm.ejs is:
So, I want to be able to enter the data in myForm.ejs and save this data in the database. But when I fill the form and press submit my req.Body is an empty object. Where is my error?
Server side you need additional parser middleware
app.use(express.json());
app.use(express.urlencoded({ extended: true })); //add this line
Client side your form should use /api/add, and not /add

Web scraping with Node.js

I'm trying to finish this task on web scraping. On my web page, I take the URL and find what located is between its <body> tags. Then, I want to output the content which was found on my web page. I learned that I can use request module for this purpose.
The problem is, I cannot show the result in my page's HTML, because I could not save the result of request's work (in POST part)
Here is my code:
var request = require("request");
const express = require('express');
const app = express();
const session = require('express-session');
const path = require('path');
const bodyParser = require('body-parser');
const router = express.Router();
app.use(session({secret: 'shhhhhhh', saveUninitialized: true, resave: true}));
app.use(bodyParser.urlencoded({extended: true}));
var sess;
router.get('/', (req, res) => {
res.sendFile(path.join(__dirname + '/index.html'));
sess = req.session;
if (app.get('done') === true) {
console.log(app.get('info')); // prints "undefined"
app.set('done', false);
res.end(`
<h1>Show other sites</h1>
<form action="/" method="POST">
<input type="text" name="site" id="site" placeholder="url"><br>
<button type="submit">go</button>
BACK
</form><br>
<hr>
<p>url: ${app.get('site')}</p>
<hr>
<div>
${app.get('info')}
</div>
`);
}
else
res.sendFile(path.join(__dirname + '/index.html'));
})
router.post('/', (req, res) => {
sess = req.session;
sess.site = req.body.site;
app.set('done', false);
if (sess.site) {
app.set('done', true);
request({
uri: `${sess.site}`,}, function(error, response, body) {
app.set('info', body); // Here I'm trying to save the scraped result
app.set('site', sess.site);
}
);
}
res.redirect('/');
})
router.get('/clear', (req, res) => {
req.session.destroy((err) => {
if (err)
return console.log(err);
res.redirect('/');
})
})
app.use('/', router);
app.listen(3000);
console.log("Running at port 3000");
Please help me find out what I'm doing wrong and how to save the result of Request module for later use.
I have to say that after following your logic it will be better to think again about it. keep in mind using a global variable is a bad practice!
been said that
you can solve the logic by following these minor changes
install node-fetch
npm i node-fetch
import it
const fetch = require('node-fetch');
then change the POST end point to
router.post('/', async (req, res) => {
sess = req.session;
sess.site = req.body.site;
app.set('done', false);
if (sess.site) {
app.set('done', true);
await fetch(sess.site)
.then(resp => resp.text()).then(body => {
console.log(body)
app.set('info', body); //Here I'm trying to save the scrapped result
app.set('site', sess.site);
})
}
res.redirect('/');
})

How to properly set up Express and mongoDB using mongoDB Node.js driver?

I am new to web development in general. I am trying to insert and find documents in a local mongoDB database through GET and POST requests. I am doing this with a Node.js/Express web server. I've managed to get something working, but I'm not sure if I'm doing the right thing.
First, I wrote client.html to send POST requests.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Client</title>
</head>
<body>
<p>Insert something into the database:</p>
<form action="/items" method="POST">
<input type="text" name="item">
<button type="submit">Submit</button>
</form>
</body>
</html>
After reading the mongoDB documentation for Node.js, I decided to write my Node.js server as follows, putting all my routes under one connection (approach 1):
const express = require("express");
const app = express();
const port = 5000;
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url, { useUnifiedTopology: true });
app.use(express.urlencoded({ extended: true }));
client.connect(function(err) {
assert.equal(null, err);
console.log("Connected successfully to server");
const db = client.db("my_db");
const itemsCollection = db.collection("items");
app.get("/", function(req, res) {
res.sendFile(__dirname + "/client.html");
});
// GET request - find documents
app.get("/items", function(req, res) {
itemsCollection.find().toArray(function(err, docs) {
assert.equal(null, err);
console.log(docs);
});
});
// POST request - insert document
app.post("/items", function(req, res) {
itemsCollection.insertOne(req.body, function(err, result) {
assert.equal(null, err);
res.redirect("/");
});
});
app.listen(port, function() {
console.log(`Listening on port: ${port}`);
});
});
However, I've also seen people create a new connection for every route, which would be something like this (approach 2):
const express = require("express");
const app = express();
const port = 5000;
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url, { useUnifiedTopology: true });
app.use(express.urlencoded({ extended: true }));
app.get("/", function(req, res) {
res.sendFile(__dirname + "/client.html");
});
// GET request - find documents
app.get("/items", function(req, res) {
client.connect(function(err) {
assert.equal(null, err);
console.log("Connected successfully to server");
const db = client.db("my_db");
const itemsCollection = db.collection("items");
itemsCollection.find().toArray(function(err, docs) {
assert.equal(null, err);
console.log(docs);
});
});
});
// POST request - insert document
app.post("/items", function(req, res) {
client.connect(function(err) {
assert.equal(null, err);
const db = client.db("my_db");
const itemsCollection = db.collection("items");
itemsCollection.insertOne(req.body, function(err, result) {
assert.equal(null, err);
res.redirect("/");
});
});
});
app.listen(port, function() {
console.log(`Listening on port: ${port}`);
});
Both approaches successfully complete the database operations. I would like to know:
Which of these approaches (if any) are recommended, and why?
Should I be calling client.close() anywhere in my server code?
Any help is appreciated, thanks!

Redirect to another url after post request (AJAX, EXPRESS)

As a part of learning node.js servers I'm working on a little log-in website. There's a site you can open and enter your username which will then be sent through an ajax post request to the server and saved into an array of all users. I wanna make it so that after you submit your username, you will be redirected to another page, unique for every username, where you will be able to see the information about you username. Sort of a 'manage your account' site.
However, I can't seem to figure out a way to redirect me to this page after I have submitted an username.
Say for example you submit a username 'kokot' and it's the 3rd username that's been submitted so far. Thus, in the 'players' array, your user object will look something like this {id: 2, username: 'kokot'}.
Now I want to redirect you to the url localhost:2000/players/2 to see the info about your specific username.
NODE JS
const express = require('express');
const server = express();
const bodyParser = require('body-parser');
server.use(bodyParser.urlencoded({extended: false}));
server.use(bodyParser.json());
let players = [];
//loads the home page
server.get('/', (req, res) =>{
res.sendFile(__dirname + '/home.html');
});
//loads the page with the list of players
server.get('/players', (req, res) =>{
res.send(players);
});
server.get('/player/:id', (req, res) =>{
res.send(players[req.params.id]);
});
//takes a new username and saves it to players array
server.post('/', (req, res) =>{
console.log('NEW PLAYER: ' + req.body.username);
players.push({
id: players.length,
username: req.body.username
});
});
/////////////////////////////////////////////////////////////////////////////
server.listen(2000, () => console.log('LISTENING ON PORT 2000'));
HTML
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<title>Home</title>
</head>
<body>
<h1>PISKVOREC</h1>
<form id="userForm">
username
<input type="text" name="text" id="userFormInput">
<input type="submit" name="Submit" id="userFormSubmit">
</form>
<script>
$(document).ready(()=>{
let homeUrl = 'http://localhost:2000';
let $userForm = $('#userForm');
let $userFormSubmit = $('#userFormSubmit');
//submits a new username to the server
$userFormSubmit.click(() =>{
$.post(homeUrl, {
username: $('#userFormInput').val()
}, function(){
console.log('USERNAME SUBMITTED TO SERVER');
});
$.
});
////////////////////
});
</script>
</body>
</html>
Thank you for you responses and ideas
Have a nice day
Sure, see below:
server.post('/', (req, res) =>{
console.log('NEW PLAYER: ' + req.body.username);
players.push({
id: players.length,
username: req.body.username
});
res.redirect(`/player/${req.body.username}`);
});
UPDATE
Demo with vanilla Express.js app
app.js
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
app.use(bodyParser.urlencoded({extended: false}));
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
app.post('/this', (req, res, next) => {
res.redirect(`/that/${req.body.username}`);
});
app.get('/that/:id', (req, res, next) => {
res.send(req.params);
});
module.exports = app;
index.hbs
<form method="post" action="/this">
<input id="username" name="username" value="vader" type="text" />
<button type="submit">Submit</button>
</form>
results in a redirect to: http://localhost:3000/that/vader

Login Form in Node.js & MongoDB (mongoose)

I'm almost beginner to web dev. I'm making a pretty basic web page for login authentication. All I'm trying to do is to check user credentials (username & password) on my LoginPage from the database (mongoose) and redirect to the next page (MainPage) if they are correct.
Login.ejs (.html) file
<html>
<head>
<title>Login</title>
</head>
<body>
<form id="form_Login" action="/MainPage" method="post">
<input id="txt_username" type="text" required>
<br><input id="txt_password" type="password" required>
<br><input type="submit" value="Login">
</form>
</body>
</html>
app.js file
var express = require('express');
var app = express();
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var User = new Schema ({
username : String,
password : String
});
mongoose.model('User',User);
mongoose.connect('mongodb://localhost:27017/MyDB');
app.set('view engine', 'ejs');
app.get('/',function(req, res) {
res.render('LoginPage');
});
app.get('/MainPage',function(req, res) {
res.render('MainPage');
});
app.post('/MainPage', function(req, res) {
// new code should come over here
res.redirect('/MainPage');
});
app.get('*', function(req, res) {
res.send('Bad Route!');
});
var server = app.listen(3000, function() {
console.log('listening on port 3000.');
});
Any help would be appreciated.
I would suggest you use the passport.js library for that.
Not only does it provide you with a good way to create local authentication, you can later on integrate google, facebook and twitter (or any oAuth) social authentication methods.
You can read the documentation which should provide you with a good starting point, or any one of these examples:
http://passportjs.org/docs
http://mherman.org/blog/2013/11/11/user-authentication-with-passport-dot-js/#.VYAS0PlViko
http://mherman.org/blog/2015/01/31/local-authentication-with-passport-and-express-4/#.VYAS0vlViko
https://scotch.io/tutorials/easy-node-authentication-setup-and-local ( I have used this one in the past)
I suggest you start by using the passport-local scheme, which will give you exactly what you need. https://github.com/jaredhanson/passport-local
Use the body-parser middleware to get your form data and use it to query your database. First you need to do a npm install body-parser. Then you could try something like the following. Note that this is very rough code however and you should probably use some other excellent libraries to handle authentication.
var express = require('express');
var app = express();
var bodyParser = require('body-parser);
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var User = new Schema ({
username : String,
password : String
});
mongoose.model('User',User);
mongoose.connect('mongodb://localhost:27017/MyDB');
app.use(bodyParser.urlencoded({ extended: true }));
app.set('view engine', 'ejs');
app.get('/',function(req,res)
{
res.render('LoginPage');
});
app.get('/MainPage',function(req,res)
{
res.render('MainPage');
});
app.post('/MainPage', function(req, res)
{
// new code should come over here
User.findOne({username: req.body.username, password: req.body.password}, function(err, user){
if(err) {
console.log(err);
}
else if(user){
res.redirect('/MainPage');
}
else {
console.log('Invalid');
}
});
});
app.get('*', function(req,res)
{
res.send('Bad Route!');
});
var server = app.listen(3000, function() {
console.log('listening on port 3000.');
});
You can use bodyPasser to get input from the html. (npm i body-parser. https://www.npmjs.com/package/body-parser).
You can use the mongoose to save the user and find the user (npm i mongoose) https://www.npmjs.com/package/mongoose.
I used here ejs.
Using the findOne you can find the register user is available or not https://mongoosejs.com/docs/api/model.html#model_Model-findOne.
//jshint esversion:6
const express = require('express');
const bodyPasser = require('body-parser');
const ejs = require('ejs');
const mongoose = require('mongoose');
const app = express();
app.use(express.static('public'));
app.set('view engine','ejs');
app.use(bodyPasser.urlencoded({ extended: true }));
mongoose.set("strictQuery", false);
mongoose.connect('mongodb://localhost:27017/userDB',{useNewUrlParser:true})
.then(() => console.log('Connected!'));
const userSchema = {
email:String,
password:String
}
const User = new mongoose.model("User",userSchema);
app.get("/",(req,res)=>{
res.render("home")
})
app.get("/register",(req,res)=>{
res.render("register")
})
app.get("/login",(req,res)=>{
res.render("login")
})
app.post("/register",(req,res)=>{
const newUser = new User({
email: req.body.username,
password: req.body.password,
});
newUser.save((err)=>{
if(err){
console.log(err);
}else{
res.render("secrets")
}
})
})
app.post("/login",(req,res)=>{
const username = req.body.username;
const password = req.body.password;
User.findOne({email:username},(err,user)=>{
if(err){
console.log(err);
}else{
if(user){
if(user.password === password){
res.render("secrets")
}
}
}
})
})
app.listen(3000,function(){
console.log("port is statrt at 3000");
})

Categories