Skip to content

Understanding methods

Understanding the app.get(), app.post(), and app.listen() Methods

In Express.js, the app.get(), app.post(), and app.listen() methods are the foundation for handling HTTP requests and starting the server. Here’s a breakdown of each method:

1. app.get()

The app.get() method is used to define a route that handles HTTP GET requests. It is typically used for retrieving data or rendering views.

app.get("/home", (req, res) => {
res.send("Welcome to the homepage!");
});

In this example, when a GET request is made to the /home route, the server responds with the message 'Welcome to the homepage!'.

2. app.post()

The app.post() method in Express is used to define a route that handles HTTP POST requests. This method is commonly used when you need to send data to the server, such as handling form submissions, login requests, or API requests.

app.post("/login", (req, res) => {
res.send("Login Successful");
});

Here, when a POST request is made to the /login route, the server will respond with the message 'Login Successful'. This is useful for scenarios like user authentication, where data (e.g., login credentials) is sent to the server for validation.

3. app.listen()

The app.listen() method is used to start the server and make it listen for incoming connections on a specified port.

app.listen(3000, () => {
console.log("Server is running on http://localhost:3000");
});

In this example, the server starts on port 3000. Once the server is running, the message Server is running on http://localhost:3000 is logged to the console.