I'm trying to access POST parameters after submitting a login form with passport. My form is as follows:
<form method="post">
<input name="username">
<input name="password">
<input type="checkbox" name="remember" value="1">
<input type="submit">
</form>
The (working) express route/callback:
app.post(
'/login',
passport.authenticate('local', {
failureRedirect: '/login',
failureFlash: true,
badRequestMessage: 'Please enter your account credentials to login.'
}),
function(req, res) {
console.log(req.param('remember'));
if(req.isAuthenticated(req, res)) {
res.redirect('/dashboard');
} else {
var errors = req.flash('error');
if(errors) {
assign['errors'] = errors;
}
res.render('login.html', {errors: errors});
}
}
);
Login works fine, everything cool. BUT: req.param('remember') is always undefined. When I remove the passport.authenticate() part, check the checkbox in my form and submit the form console correctly logs 1.
So how can I access the POST parameters when I'm also using passport.authenticate()?
Haven't used passport so far but here are two things that might cause your problem
1. Your form doesn't have an action attribute
Therefore the form doesn't know where to send the data. Try the following
<form method="post" action="/login">
<input name="username">
<input name="password">
<input type="checkbox" name="remember" value="1">
<input type="submit">
</form>
2. POST variables in express are attached to the req.body object
So instead of
console.log(req.param('remember'));
use
console.log(req.body.username);
Make sure you have the bodyParser in your express config.
req.param is used when you want to access dynamic routes
app.get('/login/:user', function(req, res) {
console.log(req.params.user)
})
// GET /login/john => 'john'
Related
I have the following route in my express application:
router.get('/edit/:id', (req, res)=> {
let searchQuery = {_id : req.params.id};
console.log(searchQuery)
Address.findOne(searchQuery)
.then(address => {
res.render('myForm', {address:address});
})
.catch(err => {
console.log(err);
});
});
and my form is:
<form action="/edit/<%= address.id %>?_method=put" method="POST">
<input type="hidden" name="_method" value="PUT">
<br>
<input type="text" value="<%= address.name %>" name="name" class="form-control">
<br>
<input type="text" value="<%= address.email %>" name="email" class="form-control">
<br>
<button type="submit" class="btn btn-info btn-block mt-3">Update User</button>
</form>
It works correctly, I can see the data getting form the mongodb into myForm. Now after I update some data in this form and click the udpdate button i get : Cannot POST /edit/62185a7efd51425bbf43e21a
Noting that I have the following route:
router.put('/edit/:id', (req, res)=> {
let searchQuery = {_id : req.params.id};
console.log(`searchQuery = ${searchQuery}`)
Address.updateOne(searchQuery, {$set: {
name: _.extend(name, req.body),
email: req.body.email,
}})
.then(address => {
res.redirect('/');
})
.catch(err => {
res.redirect('/');
});
});
It looks like express call the get and not the put in my case. Any suggestion?
The browser itself will only do GET and PUT from a <form>. So, your browser is sending a POST and your server doesn't have a handler for that POST.
The ?_method=put that you added to your URL looks like you're hoping to use some sort of method conversion or override tool on the server so that it will recognize that form POST as if it were a PUT. You don't show any server-side code to recognize that override query parameter so apparently your server is just receiving the POST and doesn't have a handler and thus you get the error CANNOT POST /edit/62185a7efd51425bbf43e21a.
There are several different middleware solutions that can perform this override. Here's one from Express: http://expressjs.com/en/resources/middleware/method-override.html and you can see how to deploy/configure it in that document.
Basically, you would install the module with:
npm install method-override
and then add this to your server:
const methodOverride = require('method-override')
// override with POST having ?_method=PUT
app.use(methodOverride('_method'));
This will look at incoming POST requests with the ?_method=PUT query string and will modify the method per the parameter in the query string so that app.put() will then match it.
This is to be used when the client can only do GET or POST and can't do other useful methods such as PUT or DELETE.
As a demonstration, this simple app works and outputs got it! back to the browser and /edit/123456789?_method=put in the server console when I press the Update User button in the HTML form.
const app = require('express')();
const path = require('path');
const methodOverride = require('method-override');
app.use(methodOverride('_method'));
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, "temp.html"));
});
app.put('/edit/:id', (req, res) => {
console.log(req.url);
res.send("got it!");
});
app.listen(80);
And, temp.html is this:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<form action="/edit/123456789?_method=put" method="POST">
<br>
<input type="text" value="hello" name="name" class="form-control">
<br>
<input type="text" value="hello#gmail.com" name="email" class="form-control">
<br>
<button type="submit" class="btn btn-info btn-block mt-3">Update User</button>
</form>
</body>
</html>
You can create chainable route handlers for a route path by using app.route(). Because the path is specified at a single location, creating modular routes is helpful, as is reducing redundancy and typos.
Note: you must change the method in side form tag to PUT
<form action="/edit/<%= address.id %>" method="put">
//Backend.js
router.route('/edit/:id')
.get((req, res) => {
res.send('Get a random book')
})
.put((req, res) => {
res.send('Update the book')
})
I have the following route in my express application:
router.get('/edit/:id', (req, res)=> {
let searchQuery = {_id : req.params.id};
console.log(searchQuery)
Address.findOne(searchQuery)
.then(address => {
res.render('myForm', {address:address});
})
.catch(err => {
console.log(err);
});
});
and my form is:
<form action="/edit/<%= address.id %>?_method=put" method="POST">
<input type="hidden" name="_method" value="PUT">
<br>
<input type="text" value="<%= address.name %>" name="name" class="form-control">
<br>
<input type="text" value="<%= address.email %>" name="email" class="form-control">
<br>
<button type="submit" class="btn btn-info btn-block mt-3">Update User</button>
</form>
It works correctly, I can see the data getting form the mongodb into myForm. Now after I update some data in this form and click the udpdate button i get : Cannot POST /edit/62185a7efd51425bbf43e21a
Noting that I have the following route:
router.put('/edit/:id', (req, res)=> {
let searchQuery = {_id : req.params.id};
console.log(`searchQuery = ${searchQuery}`)
Address.updateOne(searchQuery, {$set: {
name: _.extend(name, req.body),
email: req.body.email,
}})
.then(address => {
res.redirect('/');
})
.catch(err => {
res.redirect('/');
});
});
It looks like express call the get and not the put in my case. Any suggestion?
The browser itself will only do GET and PUT from a <form>. So, your browser is sending a POST and your server doesn't have a handler for that POST.
The ?_method=put that you added to your URL looks like you're hoping to use some sort of method conversion or override tool on the server so that it will recognize that form POST as if it were a PUT. You don't show any server-side code to recognize that override query parameter so apparently your server is just receiving the POST and doesn't have a handler and thus you get the error CANNOT POST /edit/62185a7efd51425bbf43e21a.
There are several different middleware solutions that can perform this override. Here's one from Express: http://expressjs.com/en/resources/middleware/method-override.html and you can see how to deploy/configure it in that document.
Basically, you would install the module with:
npm install method-override
and then add this to your server:
const methodOverride = require('method-override')
// override with POST having ?_method=PUT
app.use(methodOverride('_method'));
This will look at incoming POST requests with the ?_method=PUT query string and will modify the method per the parameter in the query string so that app.put() will then match it.
This is to be used when the client can only do GET or POST and can't do other useful methods such as PUT or DELETE.
As a demonstration, this simple app works and outputs got it! back to the browser and /edit/123456789?_method=put in the server console when I press the Update User button in the HTML form.
const app = require('express')();
const path = require('path');
const methodOverride = require('method-override');
app.use(methodOverride('_method'));
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, "temp.html"));
});
app.put('/edit/:id', (req, res) => {
console.log(req.url);
res.send("got it!");
});
app.listen(80);
And, temp.html is this:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<form action="/edit/123456789?_method=put" method="POST">
<br>
<input type="text" value="hello" name="name" class="form-control">
<br>
<input type="text" value="hello#gmail.com" name="email" class="form-control">
<br>
<button type="submit" class="btn btn-info btn-block mt-3">Update User</button>
</form>
</body>
</html>
You can create chainable route handlers for a route path by using app.route(). Because the path is specified at a single location, creating modular routes is helpful, as is reducing redundancy and typos.
Note: you must change the method in side form tag to PUT
<form action="/edit/<%= address.id %>" method="put">
//Backend.js
router.route('/edit/:id')
.get((req, res) => {
res.send('Get a random book')
})
.put((req, res) => {
res.send('Update the book')
})
I am trying to make a user registration express. I made the backend first and it seems to work fine since I verified it using postman. In postman, I included Content-Type as application/json, and json data in a raw data tab. However, I could not implement this back-end to the front-end when making a form (name,email,password). I got errors to include name, email, and password even though I did. I tried to console.log the req.body and got empty array. However, in the network tab in Chrome, name, email and password are included in the Form-Data and. I don't think the problem was with body-parser since there was no any problem in postman. In the network tab, I saw that the the Content-Type of the req was Content-Type: application/x-www-form-urlencoded instead of application/json, I think this might be the cause of the error.
server.js
app.use(express.json({ extended: false }));
app.get('/register', (req, res) => res.render('register'));
app.use('/api/users', require('./routes/api/users'));
api/users.js
// # route POST api/users
// #desc Register User
// #access Public
router.post(
'/',
[
check('name', 'Name is required')
.not()
.isEmpty(),
check('email', 'Please include a valid email').isEmail(),
check(
'password',
' Please enter a password with 6 or more characters'
).isLength({ min: 6 })
],
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
console.log(req.body);
return res.status(400).json({
errors: errors.array()
});
}
const { name, email, password } = req.body;
.
.
.
register.handlebars
<form class="form" action="/api/users" method="post">
<div class="form-group">
<input name="name" type="text" placeholder="Name" requried>
</div>
<div class="form-group">
<input name="email" type="email" placeholder="E-mail">
</div>
<div class="form-group">
<input name="password" type="text" placeholder="Password" minlength="6">
</div>
<input type="submit" value="Create account" class="button green-button" />
</form>
express.json() is a parser for data with Content-Type: application/json. You're using it in your code, that's why it works in Postman. In order to parse data encoded as application/x-www-form-urlencoded, you simply need to add another parser, which in this case is express.urlencoded(). Also, the extended option is accepted by urlencoded(), not by json().
app.use(express.json()) // parses application/json
app.use(express.urlencoded({ extended: true })) // parses application/x-www-form-urlencoded
Making a signup page for an app I'm going to build later. Just created a simple as can be node server, and it's running on port 3000. I created a React app with a simple form interface, running on port 3001. The user fills in the form and hits the register button, and this should send an email and password to the post route of /register.
But I get "incorrect form submission" every time. It looks like just a json object in the network pane "{email: dummy#email, password: 123}", so I'm not sure what this means...
onSubmitRegister = () => {
fetch('http://localhost:3000/register', {
method: 'post',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: this.state.email,
password: this.state.password
})
})
.then(response => response.json())
.then(data => console.log(data));
}
The node server looks like this:
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
app.use(express.static("public"));
app.use(bodyParser.urlencoded({extended: true}));
app.get("/", (req, res) => {
res.send("Hello");
})
app.post("/register", (req, res) => {
console.log(req.body);
})
app.listen(3000, () => {
console.log("Server started on port 3000");
});
For now, I just want it to console log the req.body, so I know everything is working OK before I go on to build a MongoDB database and start adding documents to collections. Stack Overflow and other forum threads I've googled suggest checking the headers are correct. This looks OK to me. Am I missing something?
EDIT: This is what the form looks like, the entire render function:
render(){
return(
<div>
<div className="text-center">
<form className="form-signin">
<h1 className="h3 mb-3 font-weight-normal">Ohaii Sign Up</h1>
<label for="inputEmail" className="sr-only">Email address</label>
<input
type="email"
id="inputEmail"
className="form-control"
placeholder="Email address"
required=""
autofocus=""
onChange={this.onEmailChange}
/>
<label for="inputPassword" className="sr-only">Password</label>
<input
type="password"
id="inputPassword"
className="form-control"
placeholder="Password"
required=""/>
<label for="inputPassword" className="sr-only">Password</label>
<input
type="password"
id="confirmPassword"
className="form-control"
placeholder="Confirm Password"
required=""
onChange={this.onPasswordChange}
/>
<div className="btn btn-block btn-social btn-google" style={{'color': '#fff'}}>
<span className="fa fa-google"></span> Sign Up with Google
</div>
<div className="btn btn-block btn-social btn-facebook" style={{'color': '#fff'}}>
<span className="fa fa-facebook"></span> Sign Up with Facebook
</div>
</form>
</div>
<button
onClick={this.onSubmitRegister}
className="btn btn-lg btn-primary btn-block"
>Register</button>
</div>
)
}
As you are sending JSON data (both your body is JSON and you are setting the JSON content type), I would recommend to change the bodyParser middleware to:
app.use(bodyParser.json());
At least, in my quick test I was then able to send data from the browser and saw it on the server. With bodyParser.urlencoded that was not the case, however, I did not get the same error as you did.
In addition, you should return some response from the server, for example, I used:
app.post("/register", (req, res) => {
console.log(req.body);
res.end("{}");
});
Was a problem specific to my environment. Just cleared the npm cache and that fixed it.
I am very to nodeJS, I have the following file as router.js:
exports.redirectlogin = function ( req, res, next ) {
// some logic
res.redirect( '/login ', {redirecturl: req.originalUrl} );
};
I am passing the req.originalUrl as a query string. Now I want to access that in login.ejs file. I tried the following ways, but none of them worked:
<div class="col-xs-6 log-in margin-20">Log In</div>
<form class="margin-20" method="POST" action="/login">
// some code
<input name="redirecturl1" type="hidden" value="<%= redirecturl %>" />
<input name="redirecturt2" type="hidden" value=<%= redirecturl %> />
<input name="redirecturl3" type="hidden" value=<% redirecturl %> />
// some code
</form>
</div>
But I am getting an error as redirecturl is not defined in all these cases. What is the correct way to fetch it in ejs file?
You're using a res.redirect, this sends the user to a new URL, it does not do any template building. In this case you will need to add code to your /login route to pull out the redirecturl from the req object and then push it into the template within your /login's res.render call. For example inside app.get('login'...);
app.get('/login', function(req, res, next) {
const redirectUrl = req.params.redirecturl;
return res.render('pages/login', {redirecturl: redirectUrl });
});