node怎么发出https请求

WBOY
发布: 2022-04-22 15:23:15
原创
4849人浏览过
方法:1、用HTTP模块的“https.get()”方法发出get请求;2、用通用的“https.request()”方法发出post请求;3、用PUT和DELETE请求,只需将“options.method”改为PUT或DELETE即可。

node怎么发出https请求

本教程操作环境:windows10系统、nodejs 12.19.0版本、Dell G3电脑。

node怎么发出https请求

了解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()方法接受两个参数:

FashionLabs
FashionLabs

AI服装模特、商品图,可商用,低价提升销量神器

FashionLabs 38
查看详情 FashionLabs
  • 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请求

PUT和DELETE请求格式与POST请求类似。 只需将options.method值更改为PUT或DELETE。

这是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();
登录后复制

推荐学习:《nodejs视频教程

以上就是node怎么发出https请求的详细内容,更多请关注php中文网其它相关文章!

相关标签:
最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号