Adding Routes for Handling request in Express JS
- Express provides methods to define routes, which map specific URL paths to corresponding server-side functions (handlers) that handle incoming requests.
- These methods come in different flavors for various HTTP methods (GET, POST, PUT, DELETE, etc.):
- app.get(path, handler): Defines a route that handles GET requests to the specified path. The handler function is called with two arguments:
- req: The request object containing information sent by the client (e.g., headers, parameters, body).
Now, when you refresh your browser, you should see “Hello from my Express app!” displayed.
- res: The response object used to send a response back to the client (e.g., send data, set status codes).
- You can use other HTTP methods like app.post, app.put, app.delete, etc., following the same syntax.
const express = require('express');
const app = express();
// Use environment variable or default to port 3000
const port = process.env.PORT || 3000;
app.get('/', (req, res) => {
// Code to handle GET requests to the root path ('/')
res.send('Hello from my Express app!');
});
app.post('/users', (req, res) => {
// Code to handle POST requests to the '/users' path
// (e.g., for creating a new user)
res.send('User creation successful!');
});
app.listen(port, () => {
console.log(`Server listening on port ${port}`);
});
Getting Started with Express JS
Express JS is a versatile, minimalist web framework for NodeJS that simplifies the development of back-end applications and APIs for web and mobile applications. Its flexibility and powerful features enable you to create robust and scalable web projects with minimal code, making it a popular choice among developers. Express is released as free and open-source software under the MIT License.
Table of Content
- Installing Express JS
- Running a simple web server in Express JS
- Adding Routes for Handling request in Express JS
- Adding Parameters to Routes in Express JS
- Modularizing Routes with Express Router:
- Adding Middleware for Processing Requests in Express JS
- Adding Error Handling Middleware in Express JS