> For the complete documentation index, see [llms.txt](https://jakekwak.gitbook.io/nestjs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://jakekwak.gitbook.io/nestjs/techniques/http-module.md).

# HTTP module

## HTTP module

[Axios](https://github.com/axios/axios)는 수십 개의 애플리케이션에서 널리 사용되는 풍부한 기능의 HTTP 클라이언트입니다. 그렇기 때문에 Nest는 이 패키지를 감싸서 기본적으로 내장된 `HttpModule`로 공개합니다. `HttpModule`은 단순히 HTTP 요청을 수행하기 위해 Axios 기반 메소드를 노출하는 `HttpService`를 내보내고 리턴 유형을 `Observables`로 변환합니다.

`HttpService`를 사용하기 위해서는 `HttpModule`을 가져와야합니다.

```typescript
@Module({
  imports: [HttpModule],
  providers: [CatsService],
})
export class CatsModule {}
```

> info **힌트** `HttpModule`은 `@nestjs/common` 패키지에서 공개됩니다.

그런 다음 `HttpService`를 삽입할 수 있습니다. 이 클래스는 `@nestjs/common` 패키지에서 쉽게 액세스할 수 있습니다.

```typescript
@@filename()
@Injectable()
export class CatsService {
  constructor(private readonly httpService: HttpService) {}

  findAll(): Observable<AxiosResponse<Cat[]>> {
    return this.httpService.get('http://localhost:3000/cats');
  }
}
@@switch
@Injectable()
@Dependencies(HttpService)
export class CatsService {
  constructor(httpService) {
    this.httpService = httpService;
  }

  findAll() {
    return this.httpService.get('http://localhost:3000/cats');
  }
}
```

모든 메소드는 `Observable` 오브젝트로 랩핑된 `AxiosResponse`를 리턴합니다.

## Configuration

[Axios](https://github.com/axios/axios)는 `HttpService`를 더욱 강력하게 만들기 위해 활용할 수 있는 많은 옵션을 제공합니다. [여기](https://github.com/axios/axios#request-config)에 대해 자세히 알아보십시오. 기본 라이브러리 인스턴스를 구성하려면 `HttpModule`의 `register()`메소드를 사용하십시오.

```typescript
@Module({
  imports: [
    HttpModule.register({
      timeout: 5000,
      maxRedirects: 5,
    }),
  ],
  providers: [CatsService],
})
export class CatsModule {}
```

이러한 모든 속성은 **axios** 생성자로 전달됩니다.

## Async configuration

모듈 옵션을 미리 전달하는 대신 비동기식으로 전달하려는 경우가 종종 있습니다. 이 경우, 비동기 데이터를 처리하는 다양한 방법을 제공하는 `registerAsync()` 메소드를 사용하십시오.

가능한 첫 번째 방법은 팩토리 기능을 사용하는 것입니다.

```typescript
HttpModule.registerAsync({
  useFactory: () => ({
    timeout: 5000,
    maxRedirects: 5,
  }),
});
```

분명히, 우리 팩토리는 다른 모든 것처럼 행동합니다 ( `async`일 수도 있고 `inject`을 통해 의존성을 주입할 수도 있습니다).

```typescript
HttpModule.registerAsync({
  imports: [ConfigModule],
  useFactory: async (configService: ConfigService) => ({
    timeout: configService.getString('HTTP_TIMEOUT'),
    maxRedirects: configService.getString('HTTP_MAX_REDIRECTS'),
  }),
  inject: [ConfigService],
});
```

또는 팩토리 대신 클래스를 사용할 수 있습니다.

```typescript
HttpModule.registerAsync({
  useClass: HttpConfigService,
});
```

위의 구성은 `HttpModule`내에서 `HttpConfigService`를 인스턴스화 하고 옵션 객체를 만드는 데 활용합니다. `HttpConfigService`는 `HttpModuleOptionsFactory` 인터페이스를 구현해야합니다.

```typescript
@Injectable()
class HttpConfigService implements HttpModuleOptionsFactory {
  createHttpOptions(): HttpModuleOptions {
    return {
      timeout: 5000,
      maxRedirects: 5,
    };
  }
}
```

`HttpModule` 내부에 `HttpConfigService`가 생성되는 것을 방지하고 다른 모듈에서 가져온 공급자를 사용하려면 `useExisting` 구문을 사용할 수 있습니다.

```typescript
HttpModule.registerAsync({
  imports: [ConfigModule],
  useExisting: ConfigService,
});
```

`HttpModule`은 가져온 모듈을 검색하여 자체적으로 인스턴스화하는 대신 이미 작성된 `ConfigService`를 재사용합니다.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://jakekwak.gitbook.io/nestjs/techniques/http-module.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
