Routes Using Express.js for Node application

Categories
Nodejs Development Website Development

Since you are here, I will assume you have knowledge of the JavaSript and Node.js

Inside the newly created directory, execute the npm init command. This command results in creating a package.json file. The package.json file is used to manage the locally installed npm packages. It also includes the meta data about the project such as name and version number.

after this , we need to install the packages we will be using for our API
The packages are:

1- ExpressJS: It’s a flexible Node.JS web appplication that has many features for web and mobile applications
2- body-parser: package that can be used to handle JSON requests.

npm install --save express body-parser

now create a index.js file and add this “Hello world” code in that file.

Now run the script using node index.js and open the browser to port 3000 on localhost and you should see the Hello World! message.

Learn the basics of Express by understanding the Hello World code

Those 4 lines of code do a lot behind the scenes.

First, we import the express package to the express value.

We instantiate an application by calling the express() method.

Once we have the application object, we tell it to listen for GET requests on the / path, using the get() method.

There is a method for every HTTP verbget()post()put()delete()patch():

app.get('/', (req, res) => { /* */ }) // get method
app.post('/', (req, res) => { /* */ }) // post method
app.put('/', (req, res) => { /* */ }) // put method
app.delete('/', (req, res) => { /* */ }) // delete method
app.patch('/', (req, res) => { /* */ }) // patch method

Above all methods accept a callback as a function – which is called when a request is started – and we need to handle it.

What’s next?

Express has all the power of Node.js under the hood.

You can do anything that you want, including connecting to a database, using any kind of caching, Redis, using sockets, and everything you can imagine doing on a server.

Leave a Reply

Your email address will not be published. Required fields are marked *