📜  node express app.listen at specific port & host - Javascript(1)

📅  最后修改于: 2023-12-03 15:17:53.262000             🧑  作者: Mango

Node Express app.listen at Specific Port and Host

If you are building a Node.js application using the Express framework, you can specify the port and host that your application listens on when it is started. This can be useful if you need to run your application on a specific port and make it accessible on a specific host.

To do this, you can use the app.listen method provided by the Express framework. This method takes two arguments: the port number to listen on and the hostname to listen on.

Listening on a Specific Port and Host

Here is an example of how to listen on a specific port and hostname:

const express = require('express');
const app = express();

const PORT = 3000;
const HOST = 'localhost';

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

app.listen(PORT, HOST, () => {
  console.log(`Server running at http://${HOST}:${PORT}/`);
});

In this example, we are setting the PORT variable to 3000 and HOST variable to localhost. We then define a route to handle requests to the root URL ('/'). When a request is made to this URL, the server responds with the string 'Hello, World!'.

We then call the app.listen method and pass in the PORT and HOST variables as arguments. We also pass in a callback function that logs a message to the console when the server starts running.

Markdown
# Node Express app.listen at Specific Port and Host

If you are building a Node.js application using the Express framework, you can specify the port and host that your application listens on when it is started. This can be useful if you need to run your application on a specific port and make it accessible on a specific host.

To do this, you can use the `app.listen` method provided by the Express framework. This method takes two arguments: the port number to listen on and the hostname to listen on.

## Listening on a Specific Port and Host

Here is an example of how to listen on a specific port and hostname:

```javascript
const express = require('express');
const app = express();

const PORT = 3000;
const HOST = 'localhost';

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

app.listen(PORT, HOST, () => {
  console.log(`Server running at http://${HOST}:${PORT}/`);
});

In this example, we are setting the PORT variable to 3000 and HOST variable to localhost. We then define a route to handle requests to the root URL ('/'). When a request is made to this URL, the server responds with the string 'Hello, World!'.

We then call the app.listen method and pass in the PORT and HOST variables as arguments. We also pass in a callback function that logs a message to the console when the server starts running.