Node.js 如何监听端口80

Node.js 如何监听端口80

Node.js是一个开源的跨平台JavaScript运行时环境。它是几乎任何类型项目的流行工具。要从Node.js中创建一个后端服务器,我们需要导入’http’模块,然后调用其createServer方法来创建一个服务器。服务器设置为监听指定的端口和主机名。当服务器准备就绪时,将调用回调函数,在本例中通知我们服务器正在运行。

语法:

导入’http’模块

const http = require('http');

创建服务器

const server = http.createServer((req,res)=>{
    // Handle request and response
});

指定端口号和主机名,并设置服务器进行监听。

server.listen(port,hostname,callback); 

当我们监听80端口时会发生什么?

HTTP的默认端口是80个- 通常大多数网络浏览器都监听默认端口。

服务器URL的语法为:

http://{hostname}:{port}/

所以,如果在服务器URL中不提到端口,则默认为80端口。简单来说, http://localhost/ 就等同于 http://localhost:80/

以下是在Node中创建服务器并使其监听80端口的代码实现。

// Importing 'http' module  
const http = require('http'); 
  
// Setting Port Number as 80  
const port = 80; 
  
// Setting hostname as the localhost 
// NOTE: You can set hostname to something  
// else as well, for example, say 127.0.0.1 
const hostname = 'localhost'; 
  
// Creating Server  
const server = http.createServer((req,res)=>{ 
  
    // Handling Request and Response  
    res.statusCode=200; 
    res.setHeader('Content-Type', 'text/plain') 
    res.end("Welcome to Geeks For Geeks") 
}); 
  
// Making the server to listen to required 
// hostname and port number 
server.listen(port,hostname,()=>{ 
  
    // Callback  
    console.log(`Server running at http://{hostname}:{port}/`); 
});

输出:

控制台输出:

Server running at http://localhost:80/

Node.js 如何监听端口80

现在在浏览器中运行http://localhost:80/。

输出:在浏览器中:

Welcome to Geeks For Geeks

Node.js 如何监听端口80

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程