【问题标题】:Send API GET request with path variables in request-promise-native在 request-promise-native 中发送带有路径变量的 API GET 请求
【发布时间】:2019-12-08 06:33:08
【问题描述】:

我想做与下面这张邮递员照片中相同的 api 调用: postman

我已经尝试过以下代码,但它只返回一些 html 而不是所需的响应

async function vendor_info() {
    const options = {
        uri: 'http://**.**.**.**/vendor/:username/pj1527',
        json: true,
        method: 'GET'
    };

    let vendor_info = undefined;
    await requestPromise(options)
                        .then((body) => {
                            // err_token = 0;
                            vendor_info = body[0];
                            console.log(body);
                            // console.log(body[0]);
                        })
                        .catch(err => {
                            vendor_info = undefined;
                            // err_token = 1;
                            // console.log(err);
                        });

    return vendor_info;
}

编辑

现在可以工作了,实际上请求中的 url 应该是 'http://.../vendor//pj1527'。

【问题讨论】:

  • 返回什么?你希望得到什么回应?
  • @bcosta12 如邮递员截图所示,与问题相关。

标签: node.js get-request request-promise


【解决方案1】:

如果您使用的是异步等待,则无需使用 then 和 catch 块,试试这样:

async function vendor_info() {
    try {
        const options = {
            uri: 'http://**.**.**.**/vendor/:username/pj1527',
            json: true,
            method: 'GET'
        };

        const vendor_info = await requestPromise(options);
        console.log('vendor_info: => ', vendor_info);
        return vendor_info;
    } catch (err) {
        console.log('Error: => ', err);
        return err;
    }
}

希望这会有所帮助:)

【讨论】:

  • 不,它仍然返回一些乱码。
  • 我仍然认为您不需要 then 并捕获如果您使用的是 async/await,您是否使用我的代码尝试了更新后的 url?
猜你喜欢
  • 1970-01-01
  • 2016-10-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-09
  • 2020-04-29
相关资源
最近更新 更多