【问题标题】:NestJs : How to implement node.js Post and Get logic in NestJsNestJs:如何在 NestJs 中实现 node.js 的 Post 和 Get 逻辑
【发布时间】:2020-07-28 10:05:37
【问题描述】:

我正在尝试在 NestJs 中实现 node.js Spotify 授权流程。

但是 HttpService Post 和 Get 函数不像在 node.js 中那样工作。

Node.js 工作示例:

var request = require('request'); // "Request" library

app.get('/callback', function(req, res) {
    var authOptions = {
      url: 'https://some-url.com/api/token',
      form: {
        code: code,
        redirect_uri: redirect_uri,
        grant_type: 'authorization_code'
      },
      headers: {
        'Authorization': 'Basic ' + (Buffer.from(client_id + ':' + client_secret).toString('base64'))
      },
      json: true
    };

    // I'm trying to implement this post in NestJS
    request.post(authOptions, function(error, response, body) {
        var options = {
          url: 'https://api.spotify.com/v1/me',
          headers: { 'Authorization': 'Bearer ' + access_token },
          json: true
        };

        request.get(options, function(error, response, body) {
          console.log(body);
        });

}

我在 NestJS 中使用 HttpService Post 方法 这不起作用:

constructor(private httpService: HttpService) {}

@Get('callback')
callback(@Request() req, @Res() res): any {
  let code = req.query.code || null;
  const url = 'https://some-url.com/api/token';
  const form = {
    code: code,
    redirect_uri: this.redirect_uri,
    grant_type: 'authorization_code'
  }
  const headers = {
    'Authorization': 'Basic ' + (Buffer.from(this.client_id + ':' + this.client_secret))
  }

  // doesn't work
  this.httpService.post( url, form, { headers: headers }).pipe(
    map((response) => {
      console.log(response);
    }),
  );
}

【问题讨论】:

    标签: nestjs


    【解决方案1】:

    您应该将return 放在this.httpService.post(...) 之前。通常,您必须订阅 post 方法返回的 Observable,但 NestJS 通过 @Get() 装饰器为您处理。

    【讨论】:

      【解决方案2】:

      你应该在你的控制器前加上“async”,然后使用“await”,后跟“toPromise()”...

      constructor(private httpService: HttpService) {}
      
      @Get('callback')
      async callback(@Request() req, @Res() res): any {
        // ... remaining code here
      
        const response = 
          await this.httpService.post(url, form, { headers: headers }).toPromise();
        return response;
      }
      

      【讨论】:

      • 你能解决这个问题吗?如果是,请点赞或标记为已解决。
      【解决方案3】:

      在 NestJS 中,您不需要将 req、res 对象发送到您的函数参数。 Nest Js 为req.bodyreq.queryreq.param 提供内置装饰器,如@Body@Query@Param。我写下调用 post 方法和 get 方法。您还可以使用 put、patch、delete 和其他方法。请在您的模块中创建一个数据传输对象文件。

      如需进一步参考,您可以查看:https://docs.nestjs.com/controllers

      export class yourController {
          constructor(private readonly httpService: HttpService) {}
      
          @Post('your-route-name')
          public postMethod(@Body() yourDTO: YourDTOClass): Promise<interface> {
              try {
                  return this.httpService.method(yourDTO);
              } catch (err) {
                  throw new HttpException(err, err.status || HttpStatus.BAD_REQUEST);
              }
          }
      
          @Get('your-route-name')
          find(@Query() query: QueryDTO): Promise<interface> {
              try {
                  return this.httpService.methodName(query);
              } catch (err) {
                  throw new HttpException(err, err.status || HttpStatus.BAD_REQUEST);
              }
          }
      }
      

      【讨论】:

        【解决方案4】:

        将此导入添加到控制器:

        import { Observable } from 'rxjs';
        import { take, tap, map } from 'rxjs/operators';
        

        然后试试这个:

        constructor(private httpService: HttpService) {}
        
        @Get('callback')
        callback(@Request() req, @Res() res): Observable<any> {
          let code = req.query.code || null;
          const url = 'https://some-url.com/api/token';
          const form = {
            code: code,
            redirect_uri: this.redirect_uri,
            grant_type: 'authorization_code'
          }
          const headers = {
            'Authorization': 'Basic ' + (Buffer.from(this.client_id + ':' + 
            this.client_secret))
          }
        
          return this.httpService.post( url, form, { headers: headers }).pipe(
            // Take first result to complete the observable..
            take(1),
            
            // [OPTIONAL] Some debug log to see the response.
            tap((response: { data: any }) => {
               console.log(`Response: ${JSON.stringify(response.data)}`);
            })
        
            // Map the response object to just return its data. 
            map((response: { data: any }) => response.data),
          );
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-06-13
          • 1970-01-01
          • 2020-03-24
          • 2020-08-10
          • 2019-05-24
          • 2019-12-25
          • 2020-07-23
          • 2020-03-21
          相关资源
          最近更新 更多