getting values from a POST method in expressJS - javascript

I'm trying to register a user in my application. This is the HTML code:
<form id="registration_form" action="register" onsubmit="return validateForm();" method="post">
Username: <input type="text" id="username" name="user[name]" /><br />
Password: <input type="password" id="password" name="user[pass]" /><br />
Repeat Password: <input type="password" id="password_repeat" name="user[pass]" /><br />
Email: <input type="text" id="email" name="user[email]" /><br />
<button type="submit" value="Register">Register</button>
<div id="error_registration" style="color: red;">
</div>
</form>
What I do in the server is taking the values of name, pass and email.
var express = require('express')
, app = express.createServer(
express.logger(),
express.cookieParser(),
express.session({ secret: 'keyboard cat' })
)
, io = require('socket.io').listen(app)
, mongoose = require('mongoose')
, schemas = require('./schemas')
, Schema = mongoose.Schema;
app.listen(80);
app.configure(function(){
app.use(express.bodyParser());
});
[...]
app.post('/register', function (req, res) {
registerUser(req, function(result){
//do something
var username = req.body.username;
});
});
My question is: why username is always undefined? Am I reading it in the wrong way? How should I then?
Thanks

Your variable is user not username.
Look:
..input type="text" id="username" name="user[name]" ..
Also you can always do console.log(req.body) to see the POST vars in the terminal.

Related

how do i get the sender email from the input form nodemailer node.js

I want the from(sender email) part to be gotten from the input but it keeps giving me the same thing as the sender and receiver the same i.e it keeps showing the user as the sender and receiver.
front end part
<p class="drop">Drop A Message</p>
<label for="name">Name:</label><br>
<input type="text" name="" id="name" class="form-inputs" placeholder="Full Name" ><br>
<label for="email">Email:</label><br>
<input type="email" name="" id="email" class="form-inputs" placeholder="Email Address" ><br>
<label for="subject">Subject:</label><br>
<input type="text" name="" id="subject" class="form-inputs" placeholder="Subject Of The Message"><br>
<label for="message">Message:</label><br>
<textarea name="" id="mainMessage" cols="30" rows="10" class="message_body" ></textarea><br>
<input type="submit" value="Send Message" class="submit_btn">
</form>
NodeJS
app.post('/', (req,res) =>{
// console.log(req.body);
const transporter = nodemailer.createTransport(smtpTransport({
service:'Gmail',
// host: 'smtp.gmail.com',
secure:false,
auth: {
user: 'horiyorrmi72#gmail.com',
pass: 'password'
}
}))
const mailOptions = {
from: req.body.email,
to : "horla_tech#protonmail.com",
subject: `${req.body.subject}`,
text : req.body.message
}
transporter.sendMail(mailOptions, (error, info) =>{
if(error){
console.log(error);
res.send('error');
}else{
console.log('Email sent' + info.response);
res.send('success');
}
})
})
app.listen(PORT, ()=> {
console.log(`server running on port: ${PORT}`);
})
Nodemailer
#nodemailer
ยท
Oct 22
Replying to
#horla_techs
Gmail does not allow to send email through their servers as 3rd person. If you try to use any other email address than your own as the sender, Gmail will override it.

Cannot POST on JS and MongoDB

I'm very new to web development, and now I'm trying to build a login page which uses HTML, CSS and Javascript for the website, and MongoDB database to store the data received from the user. I followed a few tutorials on YouTube, but for some reasons the data cannot be posted.
Here are the codes that I have so far:
(Javascript)
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded( {extended: true}));
mongoose.connect("mongodb+srv://cs196:cs196#userdata.sn7wv.mongodb.net/cs196", { userNewUrlParser: true}, {useUnifiedTopology: true} );
// create a data schema
const notesSchemaCreate = {
username: String,
email: String,
password: String,
confirm_password: String
}
const Note = mongoose.model("NoteCreate", notesSchemaCreate)
app.get("/", function(req, res) {
res.sendFile(__dirname + "/index.html");
})
app.post("/", function(req, res) {
let newNote = new Note({
username: req.body.username,
email: req.body.email,
password: req.body.password,
confirm_password: req.body.confirm_password
});
newNote.save();
})
app.listen(3000, function() {
console.log("server is running on 3000")
})
(And here are the HTML codes)
<!DOCTYPE html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta charset="utf-8">
<title>Login Site</title>
<link rel="stylesheet" href="./main.css">
</head>
<body>
<div class="container">
<!-- Create an account -->
<form class="form form--hidden" id="createAccount" method= "post" action="/">
<h1 class="form__title">Create Account</h1>
<div class="form__message form__message--error"></div>
<div class="form__input-group">
<input type="text" id="signupUsername" class="form__input" name="username" autofocus placeholder="Username">
<div class="form__input-error-message"></div>
</div>
<div class="form__input-group">
<input type="text" class="form__input" name= "email" autofocus placeholder="Email Address">
<div class="form__input-error-message"></div>
</div>
<div class="form__input-group">
<input type="password" class="form__input" name= "password" autofocus placeholder="Password">
<div class="form__input-error-message"></div>
</div>
<div class="form__input-group">
<input type="password" class="form__input" name= "confirm_password" autofocus placeholder="Confirm Password">
<div class="form__input-error-message"></div>
</div>
<button class="form__button" type="submit">Continue</button>
<p class="form__text">
<a class="form__link" href="./" id="linkLogin">Already have an account? Sign In</a>
</p>
</form>
</div>
</body>
I'm trying out the results using localhost:3000, which looks like this:
The result simply gave me cannot POST / in a new page.
Please let me know if there might be something off with my MongoDB setting, or if you want to see how the setting is right now, since I don't know what parts to show you guys and I don't want to make this post incredibly long.
Thanks in advance for anyone who can help me out with this! And I apologize in advance if my codes or this post is formatted horribly.
Each endpoint function must end the request-response cycle by sending a response ( res.send(), res.json(), res.end(), etc).
model.create() is asyncronous. Mark your function as async
So the solution would be:
app.post("/", async(req, res) => {
try {
const newUser = await Note.create({
username: req.body.username,
email: req.body.email,
password: req.body.password,
confirm_password: req.body.confirm_password
});
res.json({status: "success", message: "user created successfully", user: newUser})
} catch(error) {
res.json({status: "fail", message: error.message ? error.message : "could not create user"})
}
})
P.S: never expose your secret(mongo_uri, stripe_key, etc.) keys public.

Cannot access req.body, even when using body-parser

I am trying to get my login functionality up and running, but i am unable to access the req.body object.
When i first encountered the issue, the post route was not even getting triggered (console.log was not showing at all in terminal) and the request would eventually time out. This stopped after i added this line in the body-parser initialization:
type: 'x-www-form-urlencoded',
Now, the console.log form the route appears in the terminal, but both parameters are empty.
Router.js
const express = require('express'),
router = express.Router();
router.post('/signup', function (req, res) {
console.log(req.body.name, req.body.password);
res.send('posted');
});
module.exports = router;
app.js
const express = require('express'),
app = express(),
bodyParser = require('body-parser'),
cookieParser = require('cookie-parser'),
session = require('express-session'),
http_port = process.env.HTTP_PORT;
const http = require('http').createServer(app);
app.use(express.static(path.join(__dirname, 'public')));
app.use(
express.urlencoded({
type: 'x-www-form-urlencoded',
extended: true,
})
);
app.use(express.json());
app.use(cookieParser());
app.use(require('./backend/router'));
http.listen(process.env.PORT || http_port, () =>
console.log(`App listening on port ${http_port}`)
);
Form from index.html
<div>
<form method="POST" enctype="application/x-www-form-urlencoded">
<div class="row">
<label>Full Name</label>
<input
name="name"
type="text"
required
placeholder="Enter your name"
/>
</div>
<div class="row">
<label>Email</label>
<input
name="email"
type="email"
required
placeholder="Enter your email"
/>
</div>
<div class="row">
<label>Password</label>
<input
name="password"
type="password"
required
placeholder="Enter your password"
/>
</div>
<div class="row">
<label>Confirm Password</label>
<input
name="password_confirm"
type="password"
required
placeholder="Confirm your password"
/>
</div>
<div id="button" class="row">
<button
formmethod="POST"
formenctype="application/x-www-form-urlencoded"
type="submit"
>
Sign Up
</button>
</div>
</form>
</div>
I was not able to fix it, but i managed to find a workaroud. The info from the form is also in request.fields, so i am going to use that instead of request.body. I still would like to know why it doesn't work as normal though.
Remove type: 'x-www-form-urlencoded' in your parser and add action="http://localhost:3000/signup" to your form
Perhaps try
app.use(bodyParser.json());
instead of
app.use(express.json());

Hey I don't know where to start when inserting data into MySql from html form using node.js

I just want to know where to start with getting my html page to work with my back end code and database. I want to insert information into my table with a basic html login page but all i found were confusing sources, maybe i suck at googling but was wondering if someone can help telling me where i should start and what else i need to learn in order to achieve this,
The code below is what i managed to learn and implement.
var http = require('http');
var express = require('express');
var app = express();
var fs = require('fs');
var path = require('path');
var url = require('url');
var pages = require('html-pages');
const css = fs.readFileSync(`${__dirname}/public/art.css`, 'utf-8');
const htmlLogin = fs.readFileSync(`${__dirname}/login.html`, 'utf-8');
const htmlSignUp = fs.readFileSync(`${__dirname}/signup.html`, 'utf-8');
//static files for login
app.use('/login', express.static('./public'));
//
app.get('/login', function(req,res,next) {
res.writeHead(200, {'Content-Type' :'text/html'});
res.write(htmlLogin);
next();
}).listen(3000);
app.get("/signup", function(req,res, next) {
res.writeHead(200, {'Content-Type':'text/html'});
res.write(htmlSignUp);
});
and here is my html page
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<link href="./signup.js">
</head>
<body>
<div class="signupBox">
<h1 id="signUp">Sign Up!</h1>
<div>
<input text="text" placeholder="First Name" name="" value="">
</div>
<div>
<input text=text" placeholder="Last Name" name="Last Name" value="">
</div>
<div>
<input text="text" placeholder="Email" name="Email" value="">
</div>
<div>
<input text="text" placeholder="Password" name="Password" value="">
</div>
<input id="submit" type="button" name="" value="Sign In">
</div>
</body>
</html>
Learning how to back end with node.js and mysql just got stuck in knowing how to do this task,
var express = require('express');
var app = express();
var session = require('express-session');
var bodyParser = require('body-parser');
var path = require('path');
var http = require('http');
var sql = require('mysql');
var fs = require('fs');
var url = require('url');
var myDB = sql.createConnection({
//properties...
host: 'localhost',
user: 'root',
password: '',
database: 'sampleDB'
});
myDB.connect(function(err) {
if (err) {
console.log('There is an error');
} else {
console.log("Connected to Database");
}
});
As what I am seeing from your code, you already setup login and signup page, it it's working than now you now to save signup data you can create new route like
app.post("/register", function(req,res, next) {
console.log('request data', req.body) // you will get signup for data here.
});
and in signup for you need to add action like -
<form method="post" action="localhost:3000/register">
<h1 id="signUp">Sign Up!</h1>
<div>
<input text="text" placeholder="First Name" name="" value="">
</div>
<div>
<input text=text" placeholder="Last Name" name="Last Name" value="">
</div>
<div>
<input text="text" placeholder="Email" name="Email" value="">
</div>
<div>
<input text="text" placeholder="Password" name="Password" value="">
</div>
<input id="submit" type="button" name="" value="Sign In">
</form>
you can do same with login verification, send login detail as in below route -
app.post("/checkLogin", function(req,res, next) {
console.log('request data', req.body) // you will get login detail here.
});
Hop this help.
Update html:
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<link href="./signup.js">
</head>
<body>
<div class="signupBox">
<h1 id="signUp">Sign Up!</h1>
<form action="signup" method="POST">
<!-- it's important to define name="xx" here otherwise you'll get 'undefined' value in server side -->
<div> <input type="text" placeholder="First Name" name="firstname"> </div>
<div> <input type="text" placeholder="Last Name" name="lastname"> </div>
<div> <input type="text" placeholder="Email" name="email"> </div>
<div> <input type="password" placeholder="Password" name="password"> </div>
<input id="submit" type="button" name="" value="Sign Up">
</form>
</div>
</body>
</html>
Add this code in server side:
app.post ("/signup", function(req, res) {
// get info from form
var firstname = request.body.firstname;
var lastname = request.body.lastname;
var email = request.body.email;
var password = request.body.password;
var adduserquery = "INSERT INTO `myTable` (`firstname`,`lastname`,`email`,`password`) VALUES ('" + firstname + "', '" + lastname + "', '" + email + "', '" + password + "')";
if (email) {
// check if e-mail already exists
myDB.query('SELECT * FROM `myTable` WHERE email = ?', [email], function(error, results, fields) {
if (results.length > 0) {
response.send('This e-mail is already registered!' );
} else {
// execute query to insert data
myDB.query(adduserquery, (err, result) => {
if (err) {
return response.status(500).send(err);
}
// if insert is successful, return you to homepage
response.redirect('/home');
});
}
});
}
}
}
Thats great you have already added the express module , i woud suggest try adding form tag and give the action to the form tag , on which you want to hit eg /signup and change your input type button to submit this will workout .
<div class="signupBox">
<form action='/signup'>
<h1 id="signUp">Sign Up!</h1>
<div>
<input text="text" placeholder="First Name" name="" value="">
</div>
<div>
<input text=text" placeholder="Last Name" name="Last Name" value="">
</div>
<div>
<input text="text" placeholder="Email" name="Email" value="">
</div>
<div>
<input text="text" placeholder="Password" name="Password" value="">
</div>
<input id="submit" type="button" name="" value="Sign In">
</form>
</div>
Now if you click on submit the data can be getable inside the /signup route you have created using the req.body.NAME_VALE , once you got the value you can insert it into the database .

i am not able to fetch data from html controls using get method in nodejs and mongodb

problem in code
var userID = req.userid;
var pwd = req.pwd;
console.log("userid = " + userID + "pass = " + pwd);
the console shows values undefined instead of input data
the console shows values undefined instead of input data
I want to take data from an html file and insert into the mongo database using get method. But I am not able to fetch data from the textbox.
Code in nodejs(index.js)
const express = require('express');
const path = require('path');
const bodyparser = require("body-parser");
const mongoose = require('mongoose');
const app = express();
app.use(bodyparser());
app.use(bodyparser.urlencoded({
extended: false
}));
app.use(bodyparser.json());
app.set('port', (process.env.PORT || 1000));
mongoose.connect('mongodb://localhost/TrackDB');
var Schema = new mongoose.Schema({
username: String
, pass: String
});
var users = mongoose.model('users', Schema);
app.get("/register", function (req, res) {
var userID = req.userid;
var pwd = req.pwd;
console.log("userid = " + userID + "pass = " + pwd);
new users({
username: userID
, pass: pwd
}).save(function (err, doc) {
if (err) {
res.json(err);
}
else res.send("Successfully Registerd!");
});
console.log("users = " + users);
});
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, './public/index.html'));
});
app.listen(1000, () => {
console.log("Server Start......");
});
HTML Page (index.html)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>LOGIN/REGISTER</title>
<style>
#container {
width: 40%;
margin: auto;
border: 1px solid;
padding: 10px;
padding-left: 200px;
border-radius: 10px;
}
</style>
</head>
<body>
<div id="container">
<h1>Register</h1>
<form action="/register">
<div id="register">
<input type="text" name="userid" id="txt_userid" placeholder="Enter user id">
<br>
<input type="password" name="pwd" id="txt_pass" placeholder="Enter password">
<br>
<br>
<button type="submit" id="btn_register">Register</button>
</div>
</form>
<h1>Login</h1>
<form action="/login">
<br>
<br>
<div id="login">
<input type="text" name="user" id="userid" placeholder="Enter user id">
<br>
<br>
<input type="password" name="passw" id="pass" placeholder="Enter password">
<br>
<br>
<button type="submit" id="btn_login">Login</button>
</div>
</form>
<h1 id="msg"></h1> </div>
</body>
</html>
Try this code
var userID =req.query.userid;
var pwd = req.query.pwd
You need to use POST request, and the data won;t be available in req object. Instead it will be available in req.body
Try:
var userID = req.body.userid;
var pwd = req.body.pwd;
console.log("userid = " + userID + "pass = " + pwd);
You have to use app.post method in node.js.
And use method = post.
<form action="/register" method="post">
<div id="register">
<input type="text" name="userid" id="txt_userid" placeholder="Enter user id">
<br>
<input type="password" name="pwd" id="txt_pass" placeholder="Enter password">
<br>
<br>
<button type="submit" id="btn_register">Register</button>
</div>
</form>
Sending data to node uses post, delete, put methods. But if you wish to fetch data back from node you can use .get() method.
I suggest try to print req(i.e console.log(req)). As might be data is stored in req.body.

Categories

Resources