Node js Handle Get Post Request

Posted at: March 14, 2019 8:26 PM

How to handle GET and POST requests in Node js

In this chapter we will learn get and post request in node js with express js. We will use express-generator tool for creating a application. And we will use view engine hbs. And also get response in json format.

First of all, we will install express-generator tools globaly. If you have already installed express-generator tool then no need to install.

Intallation express-generator tool

Create a Application

Create a application using express-generator tool and set view engine hbs

Then install dependencies

GET Request

Create a get request with route path /student/:id/course/:cid in file routes/index.js

In above code passed two parameters id and cid. You can access parameter using req.params.myParamName for example req.params.id or req.params.cid

Route path: /student/:id/course/:cid
Request URL: http://localhost:3000/student/5/course/10

POST Request

Create a post request with route path /student/submit in file routes/index.js.

You can access field using req.body.fieldname. For example req.body.studentId

Complete code of index.js

routes/index.js

Create view file views/student.hbs

Edit view file views/index.hbs for create form.

Run the app with this command

Then load http://localhost:3000/ in your browser to access the app.

Conclusion

In this lesson we have learned installation of express-generator tool and create application using express-generator tool. And also learn get and post requests.

This lesson also available on YouTube
express-generator tool get request post request

Please leave comments

2 Comments