To create an HTTP server using Express.js, follow these steps:
1. Install Express.js
Make sure you have Node.js installed. Then, create a new project and install Express:
mkdir my-express-server
cd my-express-server
npm init -y
npm install express
2. Create the Server
Create a file called server.js
and add the following code:
// Import Express
const express = require('express');
// Create an Express application
const app = express();
// Define a port
const PORT = 3000;
// Define a route
app.get('/', (req, res) => {
res.send('Hello, World!');
});
// Start the server
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
Or
// creating a http server with express js
// - using conditional statement
var express = require("express");
var app = express();
app.listen(3000,(err)=>{
if(err){
console.log("error!!..");
return;
}else{
console.log("port is running");
}
})
3. Run the Server
Run the server using Node.js:
4. Test the Server
Open a browser or a tool like Postman, and navigate to http://localhost:3000
.
You should see "Hello, World!" displayed.