node.js: Can I do a POST under a router like below? - node.js

var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
router.post('/', function(req, res, next){
res.send("post works");
});
module.exports = router;
This is my index.js file.
I used express to create an app, add my own jade file which has a form in it.
Can i define a post method like that? I am new to node.js so dont really have a grasp on how this works?
I would like to add i am trying to save data to a mongodb instance.
Update: 26/11/18
I got the solution after i got the answers given down below,
I am adding the GitHub link.
I have added the working files to it.

Below is an example html login form, to make a post route work you have to make sure you define method="POST" and action="/(Insert Route)". In my example action="/login", this means that there would be a post request that is sent to /login. If I had a router setup that accepted all /login requests it would be redirected there and the router.post('/') would work.
<form action="/login" method="POST">
<p">Username</p>
<input type="text" name="username" placeholder="Enter Username">
<p>Password</p>
<input type="password" name="password" placeholder="Enter Password">
<input type="submit" name="" value="Login">
</form>

After searching the web for clarification at the end both the answers helped me out. I was trying to do a POST request from my route, i had the variable "router". What I overlooked was to add the function name to it. My html form was trying to submit to a function "/login" and My router did not have the function defined.
router.post('/login', function(req,res, next){
}
This did it.
Thanks to everyone that tried to help.

Related

Iam trying to submit an update form via put method but doesnt work [duplicate]

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')
})

Why express call my get route and not my put route?

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')
})

Redirecting to URL within a POST Request

I've been searching around but couldn't seem to find an answer to this...
I'm really new to NodeJS. I'm trying to write a server that will take the POST request when user try to login, then redirect to the home page using GET, and the home page will now display the username.
so if the url is home.html, on the page it says guest, if the url is home.html?username=adam then on the page it says adam
On my login.html, there's a form similar to this
<FORM ACTION="login.html" METHOD="POST">
<CENTER>
Username: <INPUT TYPE="text" ID="username" required=true><BR>
Password: <INPUT TYPE="password" ID="password" required=true><BR>
<INPUT TYPE="SUBMIT">
</CENTER>
</FORM>
On my server.js, I have the block trying to get the username and redirect
http.createServer(function (req, res) {
if(req.url == "login.html" && req.method == "POST")
{
req.on('data', function(chunk) {
var someData += chunk;
var username = //get from POST data
//attempt to redirect
res.writeHead(200, {"Location":"home,html?username=adam"});
res.end();
});
}
}
I was able to get the username and log it, but when I tried to redirect, the page came back blank, and the url still says login.html...
I'm not even sure if I'm doing it correctly, please help.
As you are new to nodejs please try to use REST API for communication instead of redirecting to other pages directly.
To retrieve the form data in server js you need to install body parser which is detailed here:
[https://github.com/expressjs/body-parser][1]
Then update your server js like below:
var app = require('express')();
var http = require('http').Server(app);
var bodyParser = require('body-parser')
app.use(bodyParser());
app.get('/login', function (req, res) {
res.sendfile('login.html');
});
app.get('/home', function (req, res) {
res.sendfile('home.html');
});
app.post('/login', function (req, res) {
console.log("Username:",req.body.username);
console.log("password:",req.body.password);//just for reference do not show anywhere
res.redirect('/home?username='+req.body.username);
});
http.listen(3000, function () {
console.log('listening on *:3000');
});
And your login login.html will looks like this:
<FORM ACTION="/login" METHOD="POST">
<CENTER>
Username: <INPUT TYPE="text" name="username" ID="username" required=true><BR>
Password: <INPUT TYPE="password" name="password" ID="password" required=true><BR>
<INPUT TYPE="SUBMIT">
</CENTER>
</FORM>
Do necessary action on home page as now you are avail with username on url..hope this help..let me know if any doubts. Happy coding:)

router.get not posting multiple params

Hi so I am learning basics of node.js and express, and I was trying to submit a form with two parameters and trying to get that in the same screen.
But for some reason I guess I am not sure how to use router.get to get the both input fields parameters.
Here is my js file
var express = require('express');
var router = express.Router();
router.get('/:awesomeTitle?/:awesomeAuthor?', function(req, res, next) {
res.render('node',
{title: req.params.awesomeTitle ? req.params.awesomeTitle : '' , author: req.params.awesomeAuthor ? req.params.awesomeAuthor : '' });
});
router.post('/', function(req, res, next) {
var awesomeTitle = req.body.title;
var awesomeAuthor = req.body.author;
res.redirect('/' + awesomeTitle + awesomeAuthor);
});
module.exports = router;
And here is my hbs file.
<h1> Result </h1>
<h2>{{author}}</h2>
<h1>{{title}}</h1>
<form action="/" method="post">
<input type="text"/ name="title">
<input type="text"/ name="author">
<button type="submit">Submit</submit>
</form>
So just wanted to know how to get the awesome title and author from submit to the page again in the h1 and h2 tags.
P.S I am not sure how to debug this application so.. and it doesn't show any errors, all I get is both the input fields answer combined.
It looks like you're missing a / in your redirect. Try changing the last line in your post handler to this:
res.redirect('/' + awesomeTitle + '/' + awesomeAuthor);

How to access POST data on node.js passport authentication?

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'

Resources