GET and POST is two common HTTP Requests used for building REST APIs. Both of these calls are meant for some special purpose.
As per the documentation GET requests are meant to fetch data from specified resources and POST requests are meant to submit data to a specified resource.
The Express framework provides a router() method to create HTTP endpoints. Let’s check out how to handle GET and POST requests using Express.
Table of Contents
GET request
Handling GET request in Express is pretty straightforward. You have to create instances of express and router. Here is a small snippet to achieve the same.
const router = express.Router();
const app = express();
router.get(‘/handle’,(request,response) => {
//code to perform particular action.
//To access GET variable use req.query() and req.params() methods.
});
// add router in the Express app.
app.use("/", router);
GET requests can be cached and remains in the browser history. This is why the GET method is not recommended to use for sensitive data (passwords, ATM pins, etc). You should GET requests to retrieve data from the server only.
POST Request:
Express requires an additional middleware module to extract incoming data of a POST request. This middleware is called ‘body-parser. We need to install it and configure it with Express instance.
You can install body-parser using the following command.
You need to import this package into your project and tell Express to use this as middleware. Refer to this code for a reference.
const bodyParser = require("body-parser");
const router = express.Router();
const app = express();
//Here we are configuring express to use body-parser as middle-ware.
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
router.post(‘/handle’,(request,response) => {
//code to perform particular action.
//To access POST variable use req.body()methods.
console.log(request.body);
});
// add router in the Express app.
app.use("/", router);
In this way, you can handle the GET and POST request in the Express framework.
Demo App : Login System
To demonstrate this, I am going to code one simple log-in System which will use GET request to serve HTML page to client and POST request from the client to send user name and password to Server.
Let’s create a new Node.js project.
Let’s install the dependencies.
Next, let’s create an Express web server.
const bodyParser = require("body-parser");
const router = express.Router();
const app = express();
app.listen(3000,() => {
console.log("Started on PORT 3000");
})
Run Server using the command: node server.js
We will use Express Router to handle the routes of the app. So when users request the app from a web browser, we will serve the HTML file.
res.sendfile("index.html");
});
When the user clicks on the log-in button on the HTML page we will POST the request to Server and get the response.
var user_name = req.body.user;
var password = req.body.password;
console.log("User name = "+user_name+", password is "+password);
res.end("yes");
});
Here is the complete server.js file code.
const bodyParser = require("body-parser");
const router = express.Router();
const app = express();
// add router in express app
app.use("/",router);
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
router.get(‘/’,(req, res) => {
res.sendfile(“index.html”);
});
router.post(‘/login’,(req, res) => {
var user_name = req.body.user;
var password = req.body.password;
console.log(“User name = “+user_name+”, password is “+password);
res.end(“yes”);
});
app.listen(3000,() => {
console.log("Started on PORT 3000");
})
On the front-end, we will create a simple HTML file and call the POST request using Ajax. Here is the code of the index.html page.
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> </script>
<script>
$(document).ready(function(){
var user,pass;
$("#submit").click(function(){
user=$("#user").val();
pass=$("#password").val();
$.post("http://localhost:3000/login",{user: user,password: pass}, function(data){
if(data === 'yes') {
alert("login success");
}
});
});
});
</script>
</head>
<body>
<h1>Hello people !</h1>
<input id="user" size="40" type="TEXT" />
<input id="password" size="40" type="password" />
<input id="submit" type="button" value="Submit" />
</body>
</html>
Here is a video demonstration of the app.
That’s not a logging system.
No with session created, csrf token security, …
Hi,
This log-in system was just to demonstrate how to read POST data. I have explained Session too. Please see here.
plz try to solve this …http://stackoverflow.com/questions/33363617/in-mean-im-not-able-to-diplay-list-from-database-mongodb-into-angularjs
Thank you for nice, dedicated post!
what editor did you use there in the video?
Its Atom.
Thanks for this great information.
It is very helpful. Thanks
I got one question for you, do we need to hide our endpoint here to prevent anyone can send request to your server(/login) without going thru your client page? If so, what strategy should we use?
We can prevent IP to send request to our Server. If IP is from other than allowed network then it won’t accept the request. Please look over access-control and allow-origin headers parameters of HTTP.
Once again a resourceful post. Thanks!
However, I have a doubt. Will that alert get fired? Because, you are sending ‘yes’ as response and checking for ‘done’ in the html.
When I tried with specific ‘success’ function and compare with ‘yes’, it worked.
Please correct me if I am wrong.
U are right
Amazing post for using post.
Thanks dude!
But there is a mistake.
yes -> done
to fire alert();
little mistake
yse–>done
great post!!
Thanks men !!! 😀
You don’t really need sudo on that npm
Actually in my Ubuntu system i do need that.
It’s not really good practice to tell people to do that, though.
I cannot get this example to work. The req.body is returning undefined. Any ideas to help me please?
I’l love to help.
Are you using same code or you have done some modification ?
add this line: app.use(bodyParser.json());
Was that video suppose to be helpful ? It went way too fast
It was supposed to be demo of the code not tutorial video.
you require(Body-parser) yet you do not put it in your dependencies or tell anyone to install
i did put that in dependencies !
I cannot get this example to work from another computer.
If I run the server.js on machine 1 (which as an IP of say 10.45.32.102) and go to localhost:3000 everything works as expect.
However when I try to access this page from another computer (on the same network) by doing 10.45.32.102:3000 the Simple Login page shows up but when I hit the submit button It will not POST to the server. I don’t think the jquery is working in this particular instance could you help? The example is nice. But I want people from the network to be able to access the page.
Hi John,
I need to reproduce same scenario and come up with solution.
Stay tuned.
i open a connection using java httpurl connection and write data in output stream but
am not able to read input stream using node express. iam able to read using http module not in express
how to read request input stream using express4
If i had an array of items on my server that i wanted to search from the front end and have it return valid results how would i use post and get (or either) to do this? If search took a long time how would i tackle this?
You need to use POST cause you have to pass some data to SERVER. Pass the data, use indexOf() to search in array and if found return the value.
How to tackle if its slow ? If you get so much large data then you need to implement some search Algorithm like Binary search etc to improve the speed also update the SERVER configuration.
Thanks for sharing!
Other than body-parser module, are there any other modules for parsing the POST,PUT requests?
Hi author, I want the same thing but the slight change in that, In file I have only one POST API which server the response. The requesting is coming from another server.
Input is Json like :
{
name: ‘Veeresh’,
age:100
}
Output:
Just print input in browser.
Hello I am so delighted I found your site, I really found you by
accident, while I was searching on Yahoo for something else, Anyhow
I am here now and would just like to say thanks a lot
for a fantastic post and a all round enjoyable blog (I also love the theme/design), I don’t have time to go through it all at the moment but I have saved it and also added
in your RSS feeds, so when I have time I will be back to read more, Please do keep
up the superb work.
Thank you so much for appreciation.
Will keep it up (y)
Thank you for the tutorial, short but enough to get started.
Please look at this and advice me asap please I need it 4 my project .
Here’s how my login system works. I am using was as engine with /views as folder for views. I will skip lots of details
var router =express.Router();
…..
router.get(‘/’,fxn(req,res){
res.render(‘index’); //working
}
router. post(‘/login’, function(req,res){
console.log(‘test login’); //working
res.render(‘users/index’,{ some json data here }); // not working
}
Everything is well set so no working except the part for rendering a view after a post request. Maybe an example will help using express.Router()
Hi Brian,
Its seems to be a routing issue. Please verify the route you provided for the post method is correct.
Great simple example, thanks! Saved my day, wasn’t able to get those req params, thought that “body” usage dedicated to the html elements only…
very usefull
Getting Error : “ReferenceError: setImmediate is not defined”
Where did I use setImmediate ?
i want the code to store to form data into mongo database
can you see any reason why this Angular2 observable call would cause the same Express POST to crash?
public AddProject (body : string): Observable {
let bodyString = JSON.stringify(body); // Stringify payload
let headers
= new Headers({ ‘Content-Type’: ‘application/json’,
‘Accept’: ‘q=0.8;application/json;q=0.9’ }); // … Set content type to JSON
let options = new RequestOptions({ headers: this.headers });
return this.http.post(this.actionUrlnewProject, bodyString, options)
.map(response => response.json())
.catch(this.handleError);
}
Here is the Express code….
// Insert a new resume project
app.post(“/api/resume/newProject”, function(req, res) {
//for new projects we will calculate the uid
var uid = “2”; //req.param(‘uid’);
var name = req.body.name;
console.log(“req.body.name:”, req.body.name);
var year = req.body.year;
var note = req.body.note;
var type = req.body.type;
db.collection(“wr_project”).insert(
{
“uid”:uid,
“name”:name,
“year”:year,
“note”:note,
“type”:type
},
function(err, result) {
if(err) {
res.json(err);
res.end(“yes”);
};
res.json(result);
res.end(“yes”);
});
});
Can you paste the error trace? If it is “Headers already sent” then try to remove the res.end() from error and success block and put return in error block.
Thanks a lot – very good.
For those finding this article now and dont want to use jQuery this will do the same (in ‘newer browsers):
fetch(“localhost:3000/login”,
{
method: “POST”,
body: { user: “user”, password: “pass” }
});
hey can u plz help me with hapi.js for making api ..am new with it
How to go to next page when I click submit?
Will I be able to do the same with angular as front end also?
Can someone pls tell me how to fetch data from text field inside the radio button (additional component which exposes when we click the radio button)