The express app.get() function defines the route for the HTTP GET request to a specified endpoint.
Syntax
app.get(path, callback)
Parameters
Name | Description |
path | It is a string representing the endpoint URL where the route will be accessible. |
callback | This function is executed when a GET request is made to a specific endpoint.
It accepts the following two arguments:
|
Setting up the express server
To set up an express server, you need to install it first on your local machine using the following command:
npm install express
We will create a server that requires a port number and define the port in the .env file. So, create a .env file in the root of your project and add the code below.
PORT=4000
Install the dotenv module using the following command:
npm install dotenv
To use ES Modules, you need to add type:module in the package.json file like this:
{ "type": "module", "dependencies": { "dotenv": "^16.4.5", "express": "^4.19.2" } }
Now, you can use the “import” instead of “require”.
Create a file called app.js inside the root of your project directory and add the below code:
// Import the necessary modules using ES module syntax import express from 'express'; // Import the env variables from '.env' file import { config } from 'dotenv'; // Load environment variables from .env file config(); // Create an instance of the Express application const app = express(); // Define the port number const port = process.env.PORT; // Define a GET route app.get('/article', (req, res) => { try { // Mock data to send as a response const data = { id: 1, title: "Simpsons", body: "We are homer and bart Simpsons", userId: 1 }; // Send the response back to the client res.status(200).json(data); } catch (error) { // Handle any unexpected errors console.error('Error fetching data:', error); res.status(500).json({ message: 'Internal Server Error' }); } }); // Middleware for error handling app.use((err, req, res, next) => { console.error('Unhandled error:', err); res.status(500).json({ message: 'Internal Server Error' }); }); // Start the server app.listen(port, () => { console.log(`Server is running on http://localhost:${port}`); });
In the first step, we imported the express and config. The config() function will help us load environment variables in Node.js.
Then, we created an instance of the express web application and defined a port for our application.
In the next step, we defined a GET route with the URL http://localhost:4000/article that accepts a callback function with req and res arguments.
We wrapped that function with a try-catch block to catch potential errors, making the code more resilient to errors. If something goes wrong, it will return a 500 Internal server error.
Inside the try-catch block, we defined a mock object data that has four properties:
- id = 1
- title = Simpsons
- body = We are homer and Bart, Simpsons
- userId = 1
We used the res.status(200).json(data) function to send the data in a json format to the client.
Also, I used middleware to handle errors.
Save this app.js file, go to the terminal (cmd), and start the server using this command:
node app
It will start the Node.js web server.
Test our API endpoint
We will use a POSTMAN to test our API endpoint, which is a GET handler.
Open the POSTMAN, construct a GET request, and enter the Request URL.
Here is how you can do it:
You can see that we get the JSON data response when sending the GET request.
Our final project structure looks like this:
That’s it!