Express can use various middleware for functionalities like authentication, logging, etc. For example, to use the morgan logging library:
npm install morgan
Then, in app.js:
const morgan = require('morgan');
app.use(morgan('dev'));
https://ajeetchaulagain.com/static/7cb4af597964b0911fe71cb2f8148d64/87351/express-js.png
Express can use various middleware for functionalities like authentication, logging, etc. For example, to use the morgan logging library:
npm install morgan
Then, in app.js:
const morgan = require('morgan');
app.use(morgan('dev'));
To serve static files like HTML, CSS, and JavaScript, use:
app.use(express.static('public'));
Create a public directory and put your static files there.
Add an error handling middleware to catch and respond to errors:
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something broke!');
});
You can add more routes to handle different URLs and HTTP methods. For example:
// Route for a user profile page
app.get('/user/:id', (req, res) => {
const userId = req.params.id;
res.send(User profile for user ID: ${userId});
});
const express = require('express');: Imports the Express module.const app = express();: Creates an Express application.app.use(express.json());: Adds middleware to parse JSON request bodies.app.get('/', (req, res) => {...});: Defines a route that handles GET requests to the root URL.app.post('/data', (req, res) => {...});: Defines a route that handles POST requests to /data.app.listen(port, () => {...});: Starts the server and listens on the specified port.Start your server using Node.js:
codenode app.js
Visit http://localhost:3000 in your browser to see “Hello World!” and use a tool like Postman or curl to test the /data POST endpoint.
Create a file named app.js (or index.js) in your project directory and add the following code:
const express = require('express');
const app = express();
const port = 3000;
// Middleware to handle JSON body
app.use(express.json());
// Route for the home page
app.get('/', (req, res) => {
res.send('Hello World!');
});
// Route to handle POST requests
app.post('/data', (req, res) => {
res.json({
receivedData: req.body
});
});
// Start the server
app.listen(port, () => {
console.log(Server is running on http://localhost:${port});
});
Install Express.js using npm.
codenpm install express
Run the following command to create a package.json file, which will manage your project’s dependencies.
codenpm init -y
Download and install Node.js from nodejs.org. This will include npm (Node Package Manager), which you’ll use to manage packages.
codemkdir my-express-app
cd my-express-app