簡體   English   中英

nodejs中的api請求連接問題

[英]api request connection issue in nodejs

我正在嘗試使用基本身份驗證向 web url 發出獲取請求。 但它因連接問題而失敗。

注意:當我使用“請求”庫而不是“得到”時它可以工作

我在這里想念什么?

const got = require('got');

(async () => {
  try {
    const res = await got( 
                      { 
                        url: 'https://httpbin.org/anything',
                        headers: {
                        Accept: 'application/json'
                       //Authorization: 'Basic abcjghgh8****'
                      }
                    })
    console.log('statusCode:', res.statusCode);
        console.log('body:', res.body);
    } catch (error) {
        console.log('error:', error);
    }
})();

OUTPUT:

圖書館

使用got()時,如果您想要正文,則需要使用await got(...).json()await got(...).text()或任何適合您的數據類型的選項。 默認情況下,body 還沒有被讀取(有點像fetch()接口,但更容易使用,因為你可以直接使用.json()方法)。

const got = require('got');

(async () => {
    try {
        const body = await got({
            url: 'some URL here',
            headers: {
                Accept: 'application/json',
                Authorization: 'Basic abcjghgh8****'
            }
        }).json(); // add .json() here
        console.log('body:', body);
    } catch (error) {
        console.log('error:', error);
    }
})();

而且, got().json()直接解析為正文。

您不必自己檢查 statusCode,因為如果它不是 2xx 狀態,那么它將自動拒絕 promise。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM