Гнездо Js: как реализовать node.js Опубликовать и получить логи c в NestJs - PullRequest
0 голосов
/ 15 апреля 2020

Я пытаюсь реализовать node.js Поток авторизации Spotify в Nest Js.

Но функции 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);
        });

}

Я использую метод HttpService Post в Nest JS, и он не работает:

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

Ответы [ 2 ]

0 голосов
/ 21 апреля 2020

Вы должны добавить к своему контроллеру префикс asyn c и использовать «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;
}
0 голосов
/ 15 апреля 2020

Вы должны поставить return перед this.httpService.post(...). Обычно вам нужно подписаться на Observable, возвращаемый методом post, но Nest JS обрабатывает это для вас через декоратор @Get ().

...