📜  Node.js HTTP 模块

📅  最后修改于: 2022-05-13 01:56:29.850000             🧑  作者: Mango

Node.js HTTP 模块

为了在 Node.js 中发出 HTTP 请求,Node.js 中有一个内置模块HTTP来通过 HTTP 传输数据。要在 node 中使用 HTTP 服务器,我们需要使用 HTTP 模块。 HTTP 模块创建一个 HTTP 服务器,它监听服务器端口并将响应返回给客户端。

句法:

var http = require('http');

我们可以借助http.createServer()方法创建一个 HTTP 服务器。

示例 1:
文件名:max.js

var http = require('http');
   
// Create a server
http.createServer((request, response)=>{
   
    // Sends a chunk of the response body
    response.write('Hello World!');
   
    // Signals the server that all of
    // the response headers and body 
    // have been sent
  response.end();
})
.listen(3000); // Server listening on port 3000

运行此程序的步骤:使用以下命令运行此max.js文件:

node max.js

输出:
F
d

要通过 HTTP 模块发出请求,请使用http.request()方法。

句法:

http.request(options[, callback])

示例 2:
文件名:max.js

var http = require('http');
  
var options = {
    host: 'www.geeksforgeeks.org',
    path: '/courses',
    method: 'GET'
};
  
// Making a get request to 
// 'www.geeksforgeeks.org'
http.request(options, (response) => {
  
    // Printing the statusCode
    console.log(`STATUS: ${response.statusCode}`);
}).end();

运行此程序的步骤:使用以下命令运行此max.js文件:

node max.js

输出:
d