如何在原生Node.js中发出HTTP请求

本文介绍了如何在Node.js中使用内置的HTTPS模块进行GET、POST、PUT和DELETE请求,无需任何外部依赖。通过示例代码展示了如何处理响应数据流,并指出此模块不支持Promise,适合低级别和非用户友好的用例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如何在原生Node.js中发出HTTP请求

本文翻译自How to make HTTP Requests in native Node.js

在较早的文章中,我们了解了使用各种流行的库(例如AxiosNeedle等)在Node.js中发出HTTP请求的7种不同方法。 无疑,这些库很简单,并且隐藏了在本机Node.js中处理HTTP请求的潜在复杂性。 但这还需要添加外部依赖项。

在这篇简短的文章中,您将了解Node.js本机HTTPS模块,该模块可以在没有任何外部依赖的情况下发出HTTP请求。

由于它是本机模块,因此不需要安装。 您可以通过以下代码访问它:

const https = require('https');

GET请求

是一个非常简单的示例,该示例使用HTTP模块的https.get()方法发送GET请求:

const https = require('https');

https.get('https://reqres.in/api/users', (res) => {
    let data = '';

    // called when a data chunk is received.
    res.on('data', (chunk) => {
        data += chunk;
    });

    // called when the complete response is received.
    res.on('end', () => {
        console.log(JSON.parse(data));
    });

}).on("error", (err) => {
    console.log("Error: ", err.message);
});

与其他流行的HTTP客户端收集响应并将其作为字符串或JSON对象返回的方法不同,在这里,您需要将传入的数据流连接起来以供以后使用。 另一个值得注意的例外是HTTPS模块不支持promise,这是合理的,因为它是一个低级模块并且不是非常用户友好。

POST请求

要发出POST请求,我们必须使用通用的https.request()方法。 没有可用的速记https.post()方法。

https.request()方法接受两个参数:

  • options —它可以是对象文字,字符串或URL对象。
  • callback —回调函数,用于捕获和处理响应。
    让我们发出POST请求:
const https = require('https');

const data = JSON.stringify({
    name: 'John Doe',
    job: 'DevOps Specialist'
});

const options = {
    protocol: 'https:',
    hostname: 'reqres.in',
    port: 443,
    path: '/api/users',
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'Content-Length': data.length
    }
};


const req = https.request(options, (res) => {
    let data = '';

    res.on('data', (chunk) => {
        data += chunk;
    });

    res.on('end', () => {
        console.log(JSON.parse(data));
    });

}).on("error", (err) => {
    console.log("Error: ", err.message);
});

req.write(data);
req.end();

options对象中的protocols和`port’属性是可选的。

PUT和DELETE请求

PUTDELETE请求格式与POST请求类似。 只需将options.method值更改为PUTDELETE

这是DELETE请求的示例:

const https = require('https');

const options = {
    hostname: 'reqres.in',
    path: '/api/users/2',
    method: 'DELETE'
};


const req = https.request(options, (res) => {

    // log the status
    console.log('Status Code:', res.statusCode);

}).on("error", (err) => {
    console.log("Error: ", err.message);
});

req.end();

喜欢这篇文章吗? 在TwitterLinkedIn上关注我。 您也可以订阅RSS Feed

上次更新时间:2020年10月03日

Node.js

您可能还喜欢…

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值