How do I make req.body.password not equal to undefined? - node.js

In my html I have,
<input name="password" type="password" required class="form-control" id="exampleInputPassword1">
and in my node I have,
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const urlencodedParser = bodyParser.urlencoded({ extended: false })
app.get('/login.html', (req, res) => {
res.sendFile('./login.html', {root: __dirname});
})
app.post('/login', urlencodedParser, (req,res)=>{
req.body.password
})
but, the req.body.password is undefined or empty. How do I make it actually grab what the user is inputting? It does not work for any of them but, I just used password as an example. All the packages were downloaded correctly.
Thanks.

I used the following code:
const express = require("express");
const bcrypt = require("bcrypt");
const bodyParser = require("body-parser");
const app = express();
const jsonParser = express.json();
const urlencodedParser = bodyParser.urlencoded({ extended: false });
// CHANGE THIS TO DATABASE LATER OF USERS
const users = [];
//listen for requests
app.listen(3000);
app.use(express.static(__dirname + "/public"));
app.get("/index.html", (req, res) => {
res.sendFile("./index.html", { root: __dirname });
});
app.get("/login.html", (req, res) => {
res.sendFile("./login.html", { root: __dirname });
});
app.post("/login", jsonParser, (req, res) => {
console.log("Hello");
console.log(req.body.password);
res.json(req.body.password);
});
app.get("/signup.html", (req, res) => {
res.sendFile("./signup.html", { root: __dirname });
});
app.post("/signup", urlencodedParser, (req, res) => {});
app.use((req, res) => {
res.sendFile("./404.html", { root: __dirname });
});
And when I send a POST request to the /login path using the following payload:
{
"password": "Check for Stack Overflow"
}
I get this on the console:
$ node app
Error: ENOENT: no such file or directory, stat '/root/404.html'
Hello
Check for Stack Overflow
I use the following end point: http://2886795314-3000-ollie08.environments.katacoda.com/
And I used POSTMan and got this right now:
Previous Answer...
You have to use res object to send something. For example, to send a JSON structure, you can do:
res.json(req.body.password)
So your code will be:
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
const urlencodedParser = bodyParser.urlencoded({ extended: false });
app.get("/login.html", (req, res) => {
res.sendFile("./login.html", { root: __dirname });
});
app.post("/login", urlencodedParser, (req, res) => {
res.json(req.body.password);
});
Also I could see that you are not using a .listen or export of your modules. You may as well need to listen it to a port to run! So use:
app.listen(3000, () => {
console.log("Server started in port 3000!");
});
At the end. So your complete file looks like:
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
const urlencodedParser = bodyParser.urlencoded({ extended: false });
app.get("/login.html", (req, res) => {
res.sendFile("./login.html", { root: __dirname });
});
app.post("/login", urlencodedParser, (req, res) => {
res.json(req.body.password);
});
app.listen(3000, () => {
console.log("Server started in port 3000!");
});
Also, please consider reading Express "Hello World" example. It has the best example in the easiest way possible from the original documentation.

req.body.password is kind of like a variable. It 'returns' it's value, but you're not doing anything with what it returns.
It's not clear what you mean with return. If you want to log something to a console, you can do that:
console.log(req.body.password);

Related

Troubleshooting my WebServer "The page isnโ€™t redirecting properly"

Some context, I'm using Nodejs and Express for my Web Server, I was using nginx but it failed for some reason and I tried to get help in a previous post but nothing.
When I connect to my site http works fine, https gets "The page isn't redirecting properly". When I connect to my site directly with it's IP it has https (ignoring the fact that it's still isn't really trusted since my certificates are linked to my domain) I just am trying to figure out where it's going wrong.
const express = require('express');
const https = require("https");
const http = require("http")
const fs = require('fs')
const bodyParser = require('body-parser');
var cookieParser = require('cookie-parser')
const login = require("../modules/login")
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(cookieParser())
app.set('view engine', 'ejs');
app.set('views', '../public/views');
app.use( express.static( "public" ) );
http.createServer(function (req, res) {
res.writeHead(307, { "Location": "https://www.ppealliance.com"});
res.end();
}).listen(80);
https
.createServer(
{
key: fs.readFileSync('Path to Letsencrypt Certificate'),
cert: fs.readFileSync('Path to Letsencrypt Certificate'),
},
app
)
.listen(443, () => {
console.log(https.request)
})
app.get('/', (req, res) => {
login.redirect(req, res)
});
app.get('/admin-login', (req, res, next) => {
res.render('admin-login', { title:'Admin login'});
});
app.post('/admin-login-cookies', (req, res) => {
login.cookiecheck(req, res)
});
app.get('/signup-1', (req, res) => {
res.render('signup-1', { title:'Signup Part One'});
});
app.post('/admin-login', (req, res) => {
login.login(req,res)
});
app.get('/home', (req, res) => {
login.redirect(req, res)
});

TypeError: Cannot read property 'passport' of undefined nodejs

I'm currently working on a register and login system with Express, Node, Mongoose and Passport.js and the register mostly works fine , but there's a big issue with the login system. For some reason in the method I've created passport cannot read "passport" of undefined, so something is coming up as undefined but I can't seem to figure it out.
I don't know why it's not working, any help please!!
this my code
app.js
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const cors = require('cors');
const passport = require('passport');
const mongoose = require('mongoose');
const config = require('./config/database');
mongoose.connect(config.database);
mongoose.connection.on('connected', () => {
console.log('Connected to database ' + config.database);
});
mongoose.connection.on('error', (err) => {
console.log('Database error:' + err);
});
const app = express();
const users = require('./routes/users');
const port = 3000;
app.use(cors());
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.json());
app.use(passport.initialize());
app.use(passport.session());
app.use('/users', users);
app.get('/', (req, res) => {
res.send('Invalid Endpoint');
});
app.listen(port, () =>{
console.log('Server started on port' + port);
});
users.js
const express = require('express');
const router = express.Router();
const passport = require('passport');
const jwt = require('jsonwebtoken');
const User = require('../models/user');
router.post('/register', (req, res, next) =>{
let newUser = new User({
name: req.body.name,
email: req.body.email,
username: req.body.username,
password: req.body.password
});
User.addUser(newUser, (err, user) => {
if(err){
res.json({success: false, msg:'Failed to register user'});
}else {
res.json({success: true , msg:'User registered'});
}
});
});
router.post('/authenticate', (req, res, next) =>{
res.send('AUTHENTICATE');
});
router.get('/profile', (req, res, next) =>{
res.send('PROFILE');
});
module.exports = router;
Your issue is with passport session. You need to use express session (remember to install in your dependencies) before it for it to work properly.
Your app.js should look like this:
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const cors = require('cors');
const passport = require('passport');
const mongoose = require('mongoose');
const config = require('./config/database');
const session = require("express-session");
mongoose.connect(config.database);
mongoose.connection.on('connected', () => {
console.log('Connected to database ' + config.database);
});
mongoose.connection.on('error', (err) => {
console.log('Database error:' + err);
});
const app = express();
const users = require('./routes/users');
const port = 3000;
app.use(cors());
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.json());
app.use(session({secret: "secret"});
app.use(passport.initialize());
app.use(passport.session());
app.use('/users', users);
app.get('/', (req, res) => {
res.send('Invalid Endpoint');
});
app.listen(port, () =>{
console.log('Server started on port' + port);
});
Also, keep in mind that body parser is deprecated for Express 4.16.0 or higher. It has been re-added in methods express.json() and express.urlencoded() so if your Express version falls into that category, you can change your app.js to:
const express = require('express');
const path = require('path');
const cors = require('cors');
const passport = require('passport');
const mongoose = require('mongoose');
const config = require('./config/database');
const session = require("express-session");
mongoose.connect(config.database);
mongoose.connection.on('connected', () => {
console.log('Connected to database ' + config.database);
});
mongoose.connection.on('error', (err) => {
console.log('Database error:' + err);
});
const app = express();
const users = require('./routes/users');
const port = 3000;
app.use(cors());
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(session({secret: "secret"});
app.use(passport.initialize());
app.use(passport.session());
app.use('/users', users);
app.get('/', (req, res) => {
res.send('Invalid Endpoint');
});
app.listen(port, () =>{
console.log('Server started on port' + port);
});
I suggest adding comments to your code to keep it neat as well.
In case anyone else runs into this error:
express-session deprecated undefined resave option; provide resave option
express-session deprecated undefined saveUninitialized option; provide saveUninitialized option app.
In addition to #raijin30 answer, I had to add the properties below (:
resave: true,
saveUninitialized: true
Explanation as to why, can be found at: Node JS session error: express-session deprecated.
Had the same problem and noticed that passport got updated on Septmeber 23rd. So, I decided to install the previous version via npm using
npm install --save passport#0.4.1
This solved the issue for me. Not really sure how or why it happened in the first place, but it might help you.

Node.js: res.redirect function is not working

res.redirect function is used to redirect the user to another page by clicking a button. But the function's not working. Please find the code below.
const express = require("express");
const bodyParser = require("body-parser");
const request = require("request");
const https = require("https");
const app = express();
app.use(express.static("public"));
app.use(bodyParser.urlencoded({
extended: true
}));
app.get("/", function (req, res) {
res.sendFile(__dirname + "/signup.html");
});
app.post("/failure", function (req, res) {
res.redirect("/");
});
app.post("/success", function(req, res) {
res.redirect("/");
});
app.listen(process.env.PORT || 3000, function () {
console.log("The server is running at port 3000");
});
Try moving
app.get("/", function (req, res) {
res.sendFile(__dirname + "/signup.html");
});
below your other routes and try calling again
Try changing app.post to app.get:
app.get("/success", function(req, res) {
res.redirect("/");
});

How can I prevent express-ejs-layouts for wrapping my other page?

I'm finding a page layout for node.js like laravel php have their Template for layout and it is perfect. I want to achieve it here in node.js and finally found this express-ejs-layouts but there is a problem in it that I cant see in their documentation the layout will wrap all of my pages specially my signin and signup page which have a different header and footer. How can we prevent express-ejs-layouts from wrapping my other page?
const express = require('express');
const router = express.Router();
const path = require('path');
const multer = require('multer');
const bodyParser = require('body-parser');
const mysql = require('mysql');
const app = express();
const server = require('http').createServer(app);
const expressLayouts = require('express-ejs-layouts');
// Set Database Connection
const connection=mysql.createConnection({
host:'localhost',
user:'root',
password:'',
database:'project_101'
});
connection.connect(function(error){
if(!!error) console.log(error);
else console.log('Database Connected!');
});
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.static('assets'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(bodyParser.urlencoded({extended: true}));
app.use(expressLayouts);
app.get('/',(req, res) => {
let sql = "SELECT * FROM uploads";
let query = connection.query(sql, (err, rows) => {
if(err) throw err;
res.render('index');
});
});
app.get('/signup', (req, res) => {
res.render('signup');
});
app.get('/signin', (req, res) => {
res.render('signin');
});
app.get('/unknown-user', (req, res) => {
res.render('unknown-user');
});
app.get('/profile', (req, res) => {
res.render('profile');
});
const port = process.env.PORT || 3000;
// Server Listening
server.listen(port, function () {
console.log('Server successfully running at: -',port);
});
Finally got the solution for the problem express-ejs-layouts
const express = require('express');
const expressLayouts = require('express-ejs-layouts');
app.use(expressLayouts);
You just need to declare your page as a layout and set it to false.
app.set("layout signin", false);
and render the page together with the layout.
app.get('/signin', (req, res) => {
res.render('signin', { layout: 'signin' });
});
ez fix โšก๏ธ
You can bypass the template by sending the file back.
res.sendFile(path, options, fn);
options and fn are optional.

What am I doing incorrectly with my https request?

I'm learning how to build a RESTful api with Node and Express, and I am having an issue with this https request. I am trying to make a GET request to Scryfall's api (documentation here: https://scryfall.com/docs/api), but whenever I run my server and check the browser I get a message stating
"localhost didnโ€™t send any data. ERR_EMPTY_RESPONSE".
As I'm new to using Node and Express, I'm not really sure what I am doing wrong. Here is the code for my server.js and app.js files.
//server.js
const https = require('https');
const app = require('./backend/app');
const port = process.env.PORT || '3000';
app.set('port', port);
const server = https.createServer(app); //pass the express app to the server
server.listen(port);
and
//app.js
const express = require('express');
const app = express();
app.use((req, res, next) => {
console.log('This is the first middleware');
next();
});
app.get('https://api.scryfall.com/cards/named?fuzzy=aust+com', (req, res, next) => {
res.send('${res.body.name} is the name of the card!');
});
module.exports = app;
Any help would be greatly appreciated! Thanks in advance!
๐Ÿ‘จโ€๐Ÿซ For an example, you can do it with this code below ๐Ÿ‘‡:
const express = require('express');
const axios = require('axios');
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use((req, res, next) => {
console.log('This is the first middleware');
next();
});
app.get('/', async (req, res, next) => {
try {
const result = await axios.get('https://api.scryfall.com/cards/named?fuzzy=aust+com');
res.status(200).send(result.data);
}catch(ex) {
console.log(ex.message);
}
});
app.listen(3000, () => {
console.log('Server is up');
})
๐Ÿ’ก From the code above, you can call the endpoint: localhost:3000 and than you will get the result.
I hope it's can help you ๐Ÿ™.
You can easily make a get request like this.
const express = require('express');
const app = express();
const port = 8080;
const bodyParser = require('body-parser');
//Expect a JSON body
app.use(bodyParser.json({
limit: '50mb' //Request size - 50MB
}));
app.get('/test', (req, res, next) => {
// do whatever you need here
res.status(200).send("ok");
});
app.listen(port, function () {
console.log(`Server is running.Point your browser to: http://localhost:${port}`)
});

Resources