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?

MERNスタック開発で必須のミドルウェアについて。

Posted at

MERNでの開発に限らず、モダンなWebアプリケーションで一般的に必要となる基本的なミドルウェア3つを簡単に。

1 express.json()

app.use(express.json());
  • JSONデータの解析を行うミドルウェア
  • クライアントから送られてくるJSONデータを自動的にJavaScriptオブジェクトに変換
  • 例:クライアントから{ "name": "John" }が送られてきた場合、req.body.nameで"John"にアクセス可能

2 cookieParser()

app.use(cookieParser());
  • HTTPリクエストのクッキーを解析するミドルウェア
  • クッキーの値をreq.cookiesオブジェクトとして使用可能に
  • 例:req.cookies.jwtでJWTトークンにアクセス可能

3 cors()

app.use(cors({
  origin: "http://localhost:5173",
  credentials: true,
}));
  • Cross-Origin Resource Sharing (CORS)の設定を行うミドルウェア
  • 異なるオリジン間でのリクエストを制御
  • origin: アクセスを許可するオリジン(Viteの開発サーバーなど)
  • credentials: true: クッキーやHTTP認証を含むリクエストを許可

これら3つは、モダンなWebアプリケーションで一般的に必要となる基本的なミドルウェアであり、特にフロントエンドとバックエンドが異なるポートで動作する開発環境では、これらの設定が重要となる。

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?