首頁  >  文章  >  web前端  >  node怎麼發出https請求

node怎麼發出https請求

WBOY
WBOY原創
2022-04-22 15:23:153954瀏覽

方法: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()方法接受兩個參數:

  • 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中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn