javascript 使用axios的Nestjs

mxg2im7a  于 2023-02-15  发布在  Java
关注(0)|答案(4)|浏览(132)

这个简单的演示有一个错误 * https://docs.nestjs.com/techniques/http-module *

import { Get, Controller, HttpService } from '@nestjs/common';
import { AxiosResponse } from 'axios'
import { Observable } from 'rxjs'
@Controller()
export class AppController {
  constructor(private readonly http: HttpService) {}
  @Get()
  root(): Observable<AxiosResponse<any>>  {
    return this.http.get('https://api.github.com/users/januwA');
  }
}

我该怎么办?
x一个一个一个一个x一个一个二个x

9fkzdhlc

9fkzdhlc1#

不能只返回整个AxiosResponse对象,因为它不能序列化为JSON,您最可能希望得到如下data响应:

@Get()
root() {
  return this.http.get('https://api.github.com/users/januwA').pipe(
    map(response => response.data)
  );
}

或者可选地使用Promises

@Get()
async root() {
  const response = await this.http.get('https://api.github.com/users/januwA').toPromise();
  return response.data;
}
dvtswwa3

dvtswwa32#

您必须确保将响应作为JSON处理,您可以将其作为承诺返回并获取数据,可以使用HttpService或axios

import { Get, Controller, HttpService } from '@nestjs/common';
@Controller()
export class AppController {
  constructor(private readonly http: HttpService) {}
  @Get()
      root(): {
        return this.http.get('https://api.github.com/users/quen2404')
        .toPromise()
        .then(res => res.data)
        .catch(err => /*handle error*/)
      }
}
jecbmhm3

jecbmhm33#

正如您在示例中所写,get方法返回AxiosResponse<>并包含循环引用。因此,如果您想代理Web服务https://api.github.com/users/januwA,则应返回AxiosResponse.data

import { Get, Controller, HttpService } from '@nestjs/common';
import { AxiosResponse } from 'axios'
import { Observable } from 'rxjs'
@Controller()
export class AppController {
  constructor(private readonly http: HttpService) {}
  @Get()
  root(): Observable<any>{
    return this.httpClient.get('https://api.github.com/users/quen2404')
      .pipe(map(response => response.data));
  }
}
6ie5vjzr

6ie5vjzr4#

toPromise()已弃用,因此以下是更新后的答案:

import { firstValueFrom } from 'rxjs';
import { HttpService } from '@nestjs/axios';
...
const response = await firstValueFrom(this.httpService.get('/api'));
return response.data;
}

相关问题