0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Nest.js その1 main.ts

Last updated at Posted at 2025-04-16

<サーバーサイドの流れ>

  1. main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ValidationPipe } from '@nestjs/common';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useGlobalPipes(new ValidationPipe());
  app.enableCors({
    origin: 'http://localhost:3000', // Next.js のフロントエンドのURL
    credentials: true, // Cookieの送受信を許可
    methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'], // 許可するHTTPメソッド
    allowedHeaders: ['Content-Type', 'Authorization'], // 許可するヘッダー
  });
  await app.listen(process.env.PORT ?? 8000);
}
bootstrap();



Nest.jsの開始
このコードがAppの始まり。これがないと始まりません。

const app = await NestFactory.create(AppModule);



AppModuleの中身
AppModuleが大枠。その中にUserModuleなど必要なものをインポートしていく。

imports: [
    UserModule,
    TodoModule,
    NewsModule,
    TypeOrmModule.forRoot(AppDataSource.options),
  ],



リクエスト(フロントエンドからバックエンドに情報を渡す時)のバリデーション(入力チェック)をアプリ全体で有効にする設定
間違えていたら自動でエラーを返してくれる。

app.useGlobalPipes(new ValidationPipe());




他のドメイン(例:Next.js)から NestJS API に通信を許可するため。

CORSとは
異なるドメイン間での通信を解除するために必要

app.enableCors({
    origin: 'http://localhost:3000', // Next.js のフロントエンドのURL
    credentials: true, // Cookieの送受信を許可
    methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'], // 許可するHTTPメソッド
    allowedHeaders: ['Content-Type', 'Authorization'], // 許可するヘッダー
  });





NestJS アプリケーションで サーバーを起動してポートを指定して待ち受けるために必要なコード

await app listen(...)
NestJS のサーバーを起動して、HTTPリクエストの待ち受けを開始する処理。
await を付けることで、アプリが完全に起動するまで次の処理に進まないようにしてる。


process.env.PORT
ファイルや環境変数に設定された PORT の値を読み取る。

await app.listen(process.env.PORT ?? 8000);



定義した bootstrap 関数を実行するために書く。
通常 main.ts ファイルに書かれている。

  bootstrap();
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?