DEV Community

syed muhammad bilal
syed muhammad bilal

Posted on

"Hello world" created the server in express js

First, we'll need to install Express.js using npm. Open up your terminal and run the following command:

npm install express
Enter fullscreen mode Exit fullscreen mode

Once installed, we can create a new file called server.js. In this file, we'll require the Express.js module and create a new instance of the Express.js application.

const express = require('express');
const app = express();
Enter fullscreen mode Exit fullscreen mode

Next, we'll create a simple route that responds with "Hello World!" when accessed. We can do this using the app.get() method, which creates a new route for GET requests.

app.get('/', (req, res) => {
  res.send('Hello World!');
});
Enter fullscreen mode Exit fullscreen mode

In this example, we're creating a new route for the root URL ('/') and using the res.send() method to send the text "Hello World!" as the response.
Finally, we'll start the server by calling the app.listen() method and specifying the port number to listen on.

app.listen(3000, () => {
  console.log('Server listening on port 3000');
});
Enter fullscreen mode Exit fullscreen mode

This starts the server on port 3000 and logs a message to the console when the server is listening.
Here's the complete server.js file with all the code together:

const express = require('express');
const app = express();
app.get('/', (req, res) => {
  res.send('Hello World!');
});
app.listen(3000, () => {
  console.log('Server listening on port 3000');
});
Enter fullscreen mode Exit fullscreen mode

Once you've created the server.js file, you can start the server by running the following command in your terminal:
node server.js
Now, if you open up your web browser and navigate to http://localhost:3000, you should see the message "Hello World!" displayed on the page. Congratulations, you've created a basic web server using Express.js!

Top comments (0)