繁体   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