Home > Article > Web Front-end > How to set port in nodejs
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:
const http = require('http');
This will bring in Node.js's built-in http module. This module provides classes for HTTP clients and servers.
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.
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.
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!