,

Creating Routes in Express JS with the MERN Stack

Posted by

Mern Stack – How to create a route in Express JS

Mern Stack – How to create a route in Express JS

If you’re working with the Mern Stack (MongoDB, Express, React, Node.js), you’ll need to know how to create routes in Express JS. Express is a powerful and flexible web application framework for Node.js, and is commonly used in Mern Stack development.

Step 1: Install Express

First, you’ll need to install Express in your Node.js project. You can do this using npm:

npm install express

Step 2: Create a new Express app

Once you have Express installed, you can create a new Express app by requiring the express module and calling the express() function:


const express = require('express');
const app = express();

Step 3: Define a route

To define a route in Express, you use the app.get(), app.post(), app.put(), app.delete(), or other HTTP methods provided by Express. Here’s an example of defining a simple GET route:


app.get('/', (req, res) => {
res.send('Hello, Mern Stack!');
});

This route will respond with ‘Hello, Mern Stack!’ when a GET request is made to the root URL of your app.

Step 4: Start the server

Finally, you’ll need to start the Express server so it can listen for incoming requests. You can do this by calling the app.listen() method and specifying the port number to listen on:


app.listen(3000, () => {
console.log('Server is running on port 3000');
});

Now your Express app is up and running, and you can access your route by navigating to http://localhost:3000 in your web browser.

0 0 votes
Article Rating

Leave a Reply

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@jahbyke
13 days ago

Hi Professor Kudvenkat,
I just hopped on to your most recent video to really appreciate you for your good work for more than a decade now (Not that I'm learning Express JS). Just few days ago while searching YT for SQL tutorials, I came across your SQL playlist and just watch a few videos from the playlist, my fears are gone now. I'm more than ever motivated to push ahead knowing that i have a well grounded tutor.

Thanks Sir for all you do for us. Youu will be replenished wholesomely…

1
0
Would love your thoughts, please comment.x
()
x