【问题标题】:Trying to make an API call to a remote endpoint with NestJS尝试使用 NestJS 对远程端点进行 API 调用
【发布时间】:2021-05-22 11:19:10
【问题描述】:
var unirest = require("unirest");

var req = unirest("GET", "https://edamam-edamam-nutrition-analysis.p.rapidapi.com/api/nutrition-data");

req.query({
    "ingr": "1 large apple"
});

req.headers({
    "x-rapidapi-host": "HOST",
    "x-rapidapi-key": "KEY",
    "useQueryString": true
});


req.end(function (res) {
    if (res.error) throw new Error(res.error);

    console.log(res.body);
});

我正在尝试使用该文档和参数进行 API 调用,以便根据搜索参数获取成分列表。

这是我的服务:

 async getAllNutrients(ingr: string) {
    console.log(ingr);
    const headersRequest = {
      'x-rapidapi-host': 'edamam-edamam-nutrition-analysis.p.rapidapi.com',
      'x-rapidapi-key': '5664b75c9fmsh66ac8e054422eb9p1600b8jsn878d097e8d2a',
      useQueryString: true,
    };
    const result = await this.httpService.get(
      `https://edamam-edamam-nutrition-analysis.p.rapidapi.com/api/nutrition-data` +
        ingr,
      { headers: headersRequest },
    );
    console.log(result);

    return result;
  }

这是我的控制器

@Get('/list?:ingr')
  getMacros(@Query('ingr') ingr) {
    return this.macroService.getAllNutrients(ingr);
  }

我尝试更改 QUEery 和 Param,但都没有工作。 在邮递员上,我进行了这样的 API 调用: "localhost:3000/macros/list?ingr="1 个大苹果" 我的 2 console.log 返回:

"1 large apple"
Observable { _isScalar: false, _subscribe: [Function] }
[Nest] 7460   - 2020-09-21 16:00:55   [ExceptionsHandler] Request failed with status code 404 +441782ms
Error: Request failed with status code 404

我尝试像这个例子一样使用管道:

getQuote(id){
        return this.http.get('http://quotesondesign.com/wp-json/posts/' + id)
            .pipe(
                map(response => response.data)
            ); 
    }

但结果是一样的。有什么帮助吗?

【问题讨论】:

    标签: node.js mongodb typescript nestjs


    【解决方案1】:

    看起来您的问题出在您的控制器路由中。将 @Get('/list?:ingr') 更改为 @Get('/list') 应该可以解决此问题。我相信在路径中传递?:ingr 正在设置一个带有键ingr 的参数。

    查询不需要添加到路由中。可以使用 @Query 装饰器访问它们。

    查看this 了解更多信息。

    【讨论】:

      【解决方案2】:

      在您的服务功能中

      const result = await this.httpService.get(
            `https://edamam-edamam-nutrition-analysis.p.rapidapi.com/api/nutrition-data` +
              ingr,
            { headers: headersRequest },
          );
      

      如果ingr1 large apple,那么 API URL 将变为“https://edamam-edamam-nutrition-analysis.p.rapidapi.com/api/nutrition-data1 个大苹果”。

      我认为这是一个不正确的 API URL,您不想这样调用 API。

      改成

      `https://edamam-edamam-nutrition-analysis.p.rapidapi.com/api/nutrition-data?ingr=${ingr}`,
      

      【讨论】:

        猜你喜欢
        • 2019-09-26
        • 1970-01-01
        • 1970-01-01
        • 2014-02-09
        • 2011-05-03
        • 1970-01-01
        • 2021-12-30
        • 1970-01-01
        • 2018-06-15
        相关资源
        最近更新 更多