Programming Journal

学習したことの整理用です。

NestJSでCORSを許可する

エラー

Frontend: Next.js
Backend: NestJS

で開発中にエラーが

f:id:Study-Diary:20220205160133p:plain
error

Access to XMLHttpRequest at 'http://localhost:3001/tasks' 
from origin 'http://localhost:3000' has been blocked 
by CORS policy: No 'Access-Control-Allow-Origin' header 
is present on the requested resource.

エラーの原因

'http://localhost:3001/tasks' from origin 'http://localhost:3000' has been blocked by CORS policy:

localhost:3000からlocalhost:3001へのリクエストはCORSポリシーによりブロックされたとのこと

CORSとは

オリジン間リソース共有 (CORS) - HTTP | MDN

オリジン間リソース共有 (Cross-Origin Resource Sharing, CORS) は、追加の HTTP ヘッダーを使用して、あるオリジンで動作しているウェブアプリケーションに、異なるオリジンにある選択されたリソースへのアクセス権を与えるようブラウザーに指示するための仕組みです。ウェブアプリケーションは、自分とは異なるオリジン (ドメインプロトコル、ポート番号) にあるリソースをリクエストするとき、オリジン間 HTTP リクエストを実行します。

オリジン間リクエストとは、例えば https://domain-a.com で提供されているウェブアプリケーションのフロントエンド JavaScript コードが XMLHttpRequest を使用して https://domain-b.com/data.json へリクエストを行うような場合です

対処法

No 'Access-Control-Allow-Origin' header is present on the requested resource. とあるので、Access-Control-Allow-Originをヘッダーにつけてあげる

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

// 追加
  app.enableCors({
    origin: '*',
    allowedHeaders: 'Origin, X-Requested-With, Content-Type, Accept',
  });
// ここまで

  await app.listen(3001);
}
bootstrap();

CORS | NestJS - A progressive Node.js framework