Node.js 如何发送HTTP请求

Node.js 如何发送HTTP请求

在REST API的世界里,发送HTTP请求是现代技术的核心功能。当开发者进入一个新的环境时,他们通常会学习这个功能。各种开源库,包括Node.js内置的HTTP和HTTPS模块,可以用于在Node.js中进行网络请求。

有许多方法可以创建不同类型的网络请求。在这里,我们将讨论其中的4种不同方法:

  1. 使用 AXIOS 模块
  2. 使用 SuperAgent
  3. 使用 Node-Fetch 模块
  4. 使用 HTTP 模块

在这里,我们将发送请求到https://jsonplaceholder.typicode.com/ API,并显示响应的数据。以下是我们的所有REST API。

Method REST API Detail
GET /posts Listing all resources
GET /posts/<id> Getting a resource
POST /posts Creating a resource
PUT /posts/<id> Updating a resource

设置一个新项目: 要创建一个新项目,请在终端中输入以下命令。

mkdir test
npm init -y

项目结构: 它将如下所示。

Node.js 如何发送HTTP请求

方法1: 在这个方法中,我们将使用 AXIOS 库发送请求获取资源。Axios 是一个基于 Promise 的 NodeJS 的 HTTP 客户端。你也可以在浏览器中使用它。使用 Promise 在处理异步代码(如网络请求)时具有很大的优势。

安装模块:

npm i axios

创建 index.js 并写入以下代码。

index.js

const axios = require('axios') 
  
// Make request 
axios.get('https://jsonplaceholder.typicode.com/posts/1') 
  
  // Show response data 
  .then(res => console.log(res.data)) 
  .catch(err => console.log(err))

运行应用程序的步骤: 打开终端并输入以下命令。

node index.js

输出:

Node.js 如何发送HTTP请求

方法2: 在这里,我们将使用SuperAgent库发出一个请求来创建一个资源。这是另一个在浏览器中进行网络请求的流行库,它也适用于Node.js

安装模块:

npm i superagent

用以下代码重写 index.js

index.js

const superagent = require('superagent'); 
  
// promise with async/await 
(async () => { 
  
    // Data to be sent 
    const data = { 
        title: 'foo', 
        body: 'bar', 
        userId: 1, 
    } 
  
    try { 
  
        // Make request 
        const {body} = await superagent.post( 
  'https://jsonplaceholder.typicode.com/posts') 
                             .send(data)        
        // Show response data 
        console.log(body) 
    } catch (err) { 
        console.error(err) 
    } 
  })();

运行应用程序的步骤: 打开终端并输入以下命令。

node index.js

输出:

Node.js 如何发送HTTP请求

方法3: 在这里,我们将使用node-fetch库发送一个更新资源的请求。如果您已经在浏览器中使用 Fetch ,那么它可能是您在NodeJS服务器中的好选择。

安装模块:

npm i node-fetch

用以下代码重写 index.js

index.js

const fetch = require('node-fetch'); 
  
// Propmise then/catch block 
// Make request 
fetch('https://jsonplaceholder.typicode.com/posts/1', { 
  method: 'PUT', 
  body: JSON.stringify({ 
    id: 1, 
    title: 'fun', 
    body: 'bar', 
    userId: 1, 
  }), 
  headers: { 
    'Content-type': 'application/json; charset=UTF-8', 
  }, 
}) 
  // Parse JSON data 
  .then((response) => response.json()) 
  
  // Showing response 
  .then((json) => console.log(json)) 
  .catch(err => console.log(err))

运行应用程序的步骤:

打开终端并输入以下命令。

node index.js

输出:

Node.js 如何发送HTTP请求

方法4: 我们将使用HTTP模块发送请求来获取所有资源。NodeJS内置了HTTP模块来进行网络请求。但缺点是它不像其他解决方案那样友好。在接收到数据后,你需要手动解析数据。

安装模块: 这是一个内置模块,不需要安装。只需插入并使用即可。

使用以下代码重写 index.js

index.js

// Importing https module 
const http = require('http'); 
  
// Setting the configuration for 
// the request 
const options = { 
    hostname: 'jsonplaceholder.typicode.com', 
    path: '/posts', 
    method: 'GET'
}; 
    
// Sending the request 
const req = http.request(options, (res) => { 
    let data = ''
     
    res.on('data', (chunk) => { 
        data += chunk; 
    }); 
    
    // Ending the response  
    res.on('end', () => { 
        console.log('Body:', JSON.parse(data)) 
    }); 
       
}).on("error", (err) => { 
    console.log("Error: ", err) 
}).end()

运行应用程序的步骤: 打开终端并输入以下命令。

node index.js

输出:

Node.js 如何发送HTTP请求

结论: 我个人的选择是Axios,但npm上还有一些其他流行的库,可以看一下:

  • Request
  • GOT
  • Needle

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程