您好,欢迎访问一九零五行业门户网

node怎么发出https请求

方法:1、用http模块的“https.get()”方法发出get请求;2、用通用的“https.request()”方法发出post请求;3、用put和delete请求,只需将“options.method”改为put或delete即可。
本教程操作环境: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()方法接受两个参数:
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请求的详细内容。
其它类似信息

推荐信息