server doesn't seem to see the content of html form - html

My user registration page has this form:
<form action="/users" method="post">
<input type="text" name="Ainm">
<input type="text" name="Password">
<input type="text" name="Email">
<input type="submit" value="Submit">
</form>
and the corresponding server file has:
bodyParser = require('body-parser');
app.use(bodyParser.json());
//add new user - required fields = username, password, email
app.post('/users', function (req, res) {
Users.findOne({ Ainm: req.body.Ainm })
.then(function (user) {
if (user) {
return res.status(400).send(req.body.Ainm + " Name already in use.");
} else {
Users
.create({
Ainm: req.body.Ainm,
Password:req.body.Password,
Email: req.body.Email
})
.then(function (user) { res.status(201).json(user) })
.catch(function (error) {
console.error(error);
res.status(500).send("Error: " + error);
})
}
}).catch(function (error) {
console.error(error);
res.status(500).send("Error: " + error);
});
});
But when I try to input some test data, I see
Undefined Name already in use.
Why might the value of Ainm be undefined?
Thank you.

app.use(bodyParser.json());
This is your problem.
The form data is not encoded as JSON. It will use the application/x-www-form-urlencoded encoding.
You need to use bodyParser.urlencoded().

it seems you don't have bodyparser middleware in your code (having both urlencoded and json to making API generic in future)
if you are using express below 4.16, install body-parser
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json())
else current version (4.16 and above) of express comes with inbuilt bodyParser
app.use(express.json())
app.use(express.urlencoded({ extended: true }));

Related

Pass the values from a post method via routes using mvc style

When sending a post form with username and password, I'm getting an error saying: Cannot POST /validateUser
My form looks like this:
<!DOCTYPE html>
<html>
<head>
<title>Login Form</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="contentDiv">
<form action="/validateUser" method="post">
<!-- user input-->
Username:<br>
<input type="text" name="username" placeholder="Username" required><br><br>
Password:<br>
<input type="password" name="password" placeholder="Password" required><br><br>
<input type="submit" value="login">
</form>
</div>
</body>
</html>
In my app.js I have this
const express = require('express'),
app = express(),
app.set('view engine', 'ejs')
/*For getting form input*/
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
const validationRoute = require('./routes/validationRoute')
/* Routes */
//app.post('/validateUser', validationRoute)
app.use('/validateUser', validationRoute)
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Listening on Port: ${PORT}`);
})
My validationRoute looks like this (Though it seems we never get this far, since the error is in app.js)
const express = require('express'),
router = express.Router(),
validationCon = require('../controllers/validationController')
router.get('/', validationCon.validateUser);
/*
router.get('/', (req, res) => {
console.log("URL from validate: "+req.url)
}) */
module.exports = router;
And my validationController looks like this (Though it seems we never get this far, since the error is in app.js)
const { logic } = require("../dbLogic");
module.exports = {
validateUser: async (req, res) => {
const uName = req.uName,
pwd = req.pwd;
const success = true//await logic.validateUser(uName, pwd);
if(success) {
//res.status(201).send('Login accepted');
res.render('../views/pages/secret');
}
else
res.status(400).send("Bad confidentials");
}
}
Important info!!!
Instead of doing: app.use('/validateUser', validationRoute)
If do
app.use('/validateUser', function (req, res) {
const name = req.body.username
console.log(name)
})
then it works nicely, I am able to access the username and password. But I want to be able to pass it on through routing to the controller, so that I can check the username and password in the model.
Can anyone see what's wrong with this: app.use('/validateUser', validationRoute)?
Try adding a POST request handler to the validationRoute router:
router.post('/', (req, res) => {
console.log("URL from validate: "+req.url, ' req.body: ', req.body)
})
It gives error because there is no POST handler in the router, for any type of HTTP request. Adding router.use would also work, the same as it worked with app.use in your attempt.
Read more:
Using middleware
https://expressjs.com/en/guide/using-middleware.html

JSON POST requests empty response on Mongo

I'm try to post From HTML Form To MongoDB Atlas and following the tutorial.
used:
express js
body-parser
mongoose
I can create a request but no content.
I have no clue where's the problem.
I'm supposed to show the document in MongoDB Atlas
{
"_id": "a13d1s2bc12as3a2",
"name": "Name",
"password": "password",
"_v": 0
}
but now like this:
{
"_id": "a13d1s2bc12as3a2",
"_v": 0
}
I can connect the mongoDB.
Here my code:
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const urlencoded = require("body-parser/lib/types/urlencoded");
app.use(bodyParser.urlencoded({extended: true}));
//connect mongodb
mongoose.connect("mongodb+srv://comp3421:password#cluster.o06sg.mongodb.net/db", {useNewUrlParser: true, useUnifiedTopology: true})
//create dataSchema
const notesSchema = {
username:String,
password:String
}
const Note = mongoose.model("Note", notesSchema);
//get function
app.get("/", function(req, res){
res.sendFile(__dirname + "/try.html");
})
//insert into mongodb
app.post("/", function(req, res){
let newNote = new Note({
username: req.body.username,
password: req.body.password
});
newNote.save();
res.redirect('/');
})
app.listen(3000, function(){
console.log("server is running on 3000")
})
This part is try.html and the main part of the html:
<form action="/" method="post" enctype="multipart/form-data">
<div class="f input">
<label>Username</label>
<input type="text" name="username">
</div>
<div class="f input">
<label>Password</label>
<input type="password" name="password" >
</div>
<div>
<input type="submit" value="Create account">
</div>
</form>
You need to parse request body.
You have to mention below line.
app.use(bodyParser.json());

Cannot POST /ha use more then one FORM

I was trying to send more then one FORM, but I get an error.
The first FORM works the second one doesn't. It's the same form.
The second one gives me an error Cannot POST /ha
<body>
<form action="/ha" method="post">
<input type="text" name="user">
<input type="submit" value="Senden">
</form>
<form action="/Gehalt" method="post">
<input type="text" name="user">
<input type="submit" value="Senden">
</form>
</body>
this is my test.js
const sqlite3 = require('sqlite3').verbose();
const express = require('express');
const bodyParser = require('body-parser')
var app = express();
let Gehalt
let r
app.use(bodyParser.urlencoded({
extended: true
}));
let db = new sqlite3.Database('memory.sqlight3', sqlite3.OPEN_READWRITE, (err) => {
if (err) {
console.error(err.message);
}
console.log('Connected to the chinook database.');
});
app.get('/', function(req, res) {
res.sendFile(__dirname + '/test.html');
});
app.post('/ha', function(req, res) {
console.log("Yout got it");
r = req.body.user;
var stmt = db.prepare('INSERT INTO lorem (Salary) VALUES(?);');
stmt.run(r);
stmt.finalize();
db.close();
});
app.post('/Gehalt', function(req, res) {
console.log("Yout got it");
r = req.body.user;
var stmt = db.prepare('INSERT INTO lorem (Outgoings) VALUES(?);');
stmt.run(r);
stmt.finalize();
db.close();
});
app.listen(3100, function() {
console.log('GO to Port 3100');
});
What did I do wrong?

html input returns undefined with express

So I'm learning how to do Node.js with Mysql for the first time. I'm currently following this tutorial(https://hackernoon.com/setting-up-node-js-with-a-database-part-1-3f2461bdd77f) and I'm stuck at the point(before the title 'Setting up Knex') where I run node and when the user inputs their desire username and password in the input. In the tutorial it says it should console.log back the users' username and password but instead I get undefined.
Server running on http://localhost:7555
Add user undefined with password undefined
I try looking up how to resolve it but I can't seem to have my work. I'm not quite sure if it is express or html that may seem outdated. This is what I have now.
index.html
<!DOCTYPE html>
<html>
<head>
<title>Node Database Tutorial</title>
</head>
<body>
<h1>Create a new user</h1>
<form action="/CreateUser", method="post">
<input type="text" class="username" placeholder="username">
<input type="password" class="password" placeholder="password">
<input type="submit" value="Create user">
</form>
<script src="/app.js"><script>
</body>
</html>
app.js
const CreateUser = document.querySelector('.CreateUser')
CreateUser.addEventListener('submit', (e) => {
e.preventDefault()
const username = CreateUser.querySelector('.username').value
const password = CreateUser.querySelector('.password').value
post('/createUser', { username, password })
})
function post(path, data){
return window.fetch(path, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
}
index.js
const express = require('express')
const bodyParser = require('body-parser')
const store = require('./store')
const app = express()
app.use(express.static('public'))
app.use(bodyParser.urlencoded({extended:false}))
app.use(bodyParser.json())
var jsonParser = bodyParser.json()
var urlencodedParser = bodyParser.urlencoded({extended: false})
app.post('/createUser', urlencodedParser, function(req, res){
if (!req.body) return res.sendStatus(400)
store.createUser({
username: req.body.username,
password: req.body.password
})
.then(() => res.sendStatus(200))
})
app.listen(7555, () => {
console.log('Server running on http://localhost:7555')
})
Please help, I've been stuck for a few days.
edit: this is where my console.log is at(store.js)
module.exports = {
createUser({ usern-ame, password }) {
console.log(`Add user ${username} with password ${password}`)
return Promise.resolve()
}
}
In your form there is no class='CreateUser' in your <form> tag. Add the class there.
Also, in your app.post there is no console.log
The store.js is syntactically incorrect, it should be:
module.exports = {
createUser: function({ username, password }) {
console.log(`Add user ${username} with password ${password}`)
return Promise.resolve()
}
}

How do I POST data into MongoDB database using node.JS?

the code below is pretty messy so don't judge too much! I am trying to POST a basic user profile into my database, i don't think i am far off but i keep getting a 404.
im pretty knew to all of these technologies so could somebody please enlighten me as to what i have done wrong.
node.js POST method
var express = require('express');
var router = express.Router();
var mongo = require('mongodb');
var assert = require('assert');
var url = 'mongodb://localhost:27017/local';
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('signIn', { title: 'signIn' });
});
router.get('/getData', function(req, res, next){
mongo.connect(url, function (err, db) {
assert.equal(null, error);
var cursor = db.collection('userData').find();
cursor.forEach(function(doc, err){
assert.equal(null, err);
resultArray.push(doc);
}, function() {
db.close();
res.render('index', {items: resultArray});
} );
});
});
router.post ('/insert', function(req,res,next) {
var item = {
email: req.body.email,
firstName: req.body.firstName,
lastName: req.body.lastName,
password: req.body.password
};
mongo.connect(url, function (err, db) {
assert.equal(null, err);
db.collection('userData').insertOne(item, function (err, result) {
assert.equal(null, err);
console.log('item has been inserted');
db.close;
});
});
res.redirect('/');
});
module.exports = router;
form HTML
<!DOCTYPE html>
<html lang="en">
<head>
<title>SignIn Page</title>
<link rel="stylesheet" type="text/css" href="/stylesheets/signIn.css"/>
</head>
<body>
<div class="background">
<div class="loginFormWrapper">
<form action="/users/submit" method="POST">
<div class="loginForm">
<label for="firstName">First name:</label>
<input type="text" class="form-control" id="firstName" name="firstName" placeholder="first name">
<label for="lastName">Last name:</label>
<input type="text" class="form-control" id="lastName" name="lastName" placeholder="last name">
<label for="email">Email address:</label>
<input type="email" class="form-control" name="email" id="email" placeholder="email">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" name="password" id="password" placeholder="password">
</div>
<div class="checkbox">
<label><input type="checkbox"> Remember me</label>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
<form action="users" method="GET">
<button type="submit" class="btn btn-default">get result</button>
</form>
</div>
</div>
</body>
</html>
App.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var validate = require('form-validate');
var mongoose = require('mongoose');
var index = require('./routes/index');
var users = require('./routes/users');
var About = require('./routes/about');
var signIn = require('./routes/signIn');
var contact = require('./routes/contact');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
app.use('/users', users);
app.use('/About', About);
app.use('/signIn', signIn);
// app.use('/contact', contact);
//catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
user.js
var express = require('express');
var app = require("mongoose");
var router = express.Router();
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
module.exports = router;
A quick reminder, the post() method just gets the data from the <form> you specify. For you to be able to get that data you'd have to do something like this.
app.js
const express = require('express)
const mongoose = require('mongoose)
var app = express()
mongoose.connect('mongodb://localhost:"yourPortHere"/"mongoDBhere"')
Now post needs the body parser in order to be able to retrieve the data and sort of "translate it" to JS, for that you need the body parser.
app.use(bodyParser.urlencoded({extended: false})) //Post Body Parser
Now let's get to the post
app.post("/action", (req, res) => {
var userData = {
username: req.body.username,
password: req.body.password
}
For the moment userData is going to hold the data you just retrieved from the <form>
Remember that action="/YourActionHere is the identifier for the app.post("/YourActionHere") so those two have to match, otherwise you will not get the data.
To save it to MongoDB you first need to create a model of the object you want to store, if MongoDB has a Database named movies with a directory named films on it you first have to create a Model named film since mongoose will save it in the directory films (<- By directory I mean collection)
So: in folder Models you create a model of the object
const mongoose = require('mongoose')
const Schema = mongoose.Schema
var film = new Schema({
title: String,
year: String,
director: String
})
module.exports = mongoose.model("movie", movieSchema)
To be able to use that new Schema you have to import it in you app.js with
var Film = require('pathToFilmSchema')
Now in your post you will save userData to that Schema, and mongoose will store it in the collection specified in its .js.
app.post("/action", (req, res) => {
var userData = {
title: req.body."name",
year: req.body."name",
director: req.body.""
}
new Film(userData)
})
If the structure is the same de Data in that variable will be stored in a Schema, then you just have to call the method .save(), which you can call right after like this
newFil(userData)
.save()
Now mongoose will store a new object with film Schema into the database you have connected at the top. Keep in mind that, if you don't have a collection named film mongoDB will create one collection named films (the plural, always) and store the Schema there.
After saving you can res.redirect() to "/" or render another page, that's up to you.
You have posted to url users/submit but i don't see any API for users/submit . You have said to use users for /users urls but have you defined the /submit within /users?
You could go through this
Routing in expressjs
Inside your app.post function you should have something like this:
let MongoClient = require('mongodb').MongoClient;
let connectionUrl = "mongodb://localhost:27017/";
// or
// let connectionUrl = "mongodb+srv://<username>:<password>#<your-cluster-url>/test?retryWrites=true&w=majority";
// creating the message object
let obj = {"text" : "Something"};
console.log("OBJ: " + obj);
MongoClient.connect(connectionUrl, function(err, client) {
if (err) throw err;
console.log("Connected correctly to server");
// if database and collection do not exist they are created
var db = client.db('YourDatabase')
db.collection("YourCollection").insertOne(obj, function(err, res) {
if (err) throw err;
console.log("1 message inserted");
client.close();
});
});