nodejs中的api请求连接问题

问题描述

我正在尝试使用基本身份验证向 Web url 发出 get 请求。但它因连接问题而失败。

注意:当我使用“请求”库而不是“得到”时它有效

在这里错过了什么?

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);
    }
})();

输出

图书馆

解决方法

使用 got() 时,如果需要正文,则需要使用 await got(...).json()await got(...).text() 或任何适合您的数据类型的选项。默认情况下,正文尚未被读取(有点像 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 状态,那么它会自动拒绝承诺。