Home >Web Front-end >Front-end Q&A >How to set port in nodejs

How to set port in nodejs

PHPz
PHPzOriginal
2023-05-25 16:19:391352browse

In Node.js, how to set the port?

When you need to create a Node.js application, you want to ensure that the application can respond to HTTP requests. This requires using a port to listen for client requests. Node.js provides an easy way to set ports.

Use the following steps to set up a port in Node.js:

  1. The first step is to add the following code to your JavaScript file:
const http = require('http');

This will bring in Node.js's built-in http module. This module provides classes for HTTP clients and servers.

  1. Next, create an HTTP server. To do this, use the following code:
const server = http.createServer((req, res) => {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/plain');
    res.end('Hello World!');
});

Here, we use the createServer() method to create an HTTP server. The server's response behavior is implemented in the callback function. The callback function here receives two parameters: req represents the client request, res represents the server response.

This is a basic response, which returns a status code of 200 by sending a "Hello World" message to the client, indicating that everything is OK.

  1. Next, listen to the port. To do this, use the following code:
const port = 3000;
server.listen(port, () => {
    console.log(`Server running at http://localhost:${port}/`);
});

Here, we specify that the port the server wants to listen on is 3000. Then, use the listen() method to start the HTTP server. A message is output in the callback function indicating that the server is running. You can visit http://localhost:3000/ in your browser to view the output message.

  1. Finally, run the application. To do this, enter the following into the console:
node filename.js

Here, you need to replace "filename.js" with the name of your JavaScript file.

This is the process of setting a port in Node.js. You can implement any operation in the response, such as rendering HTML pages, responding to JSON data, etc. If you want to learn more about the concepts and usage of Node.js, please refer to the official documentation of Node.js.

The above is the detailed content of How to set port in nodejs. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:javascript or nodejsNext article:javascript or nodejs