Express is a minimal, flexible web application framework for Node.js that provides a robust set of features to develop web and mobile applications. It simplifies handling routes, requests, and responses, allowing developers to build web servers with ease. Let’s see how we can create an Express app. server with express & node.js
Install Express
$ npm install express
Create the Server File
Create a new file named server.js
(or app.js
) and add the following code:
// Import the express module
const express = require('express');
// Create an instance of Express
const app = express();
// Define a port to listen on
const PORT = process.env.PORT || 3000;
// Set up a basic route
app.get('/', (req, res) => {
res.send('Hello, World!');
});
// Start the server
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
Run the Server
To start your Node.js server, run:
$ node server.js
Now, your server will be running, and you can visit http://localhost:3000
in your browser. You should see “Hello, World!” displayed.
express()
: This creates an instance of an Express application.app.get()
: This defines a route handler for GET requests on the specified path (/
in this case).app.listen()
: This starts the server and listens on the specified port.
That’s a basic setup for creating an HTTP server with Express in Node.js!
Leave a Reply