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?

Express.js×TypeScriptアプリのログインをPostmanで確認する方法【PostgreSQL】

0
Posted at

前回記事の続き

今回は、ログインをPostmanで実行した時のデータの挙動はどうなるのかを確認してみたいと思います。

Postmanを使ってログインの挙動を確認

方法

1. Method設定

左側のMethodをPOSTに設定します。

2. URL

URL欄にはこれだけ入力します。

http://localhost:3000/auth/login

3. Header設定

Headersタブを下記のように設定します。
image.png

image.png

4. Body設定

Body → raw → JSON

登録したユーザー情報を入れます。

{
  "email": "test@example.com",
  "password": "password123"
}

5.Send

AuthController.login では:

AuthController.ts
const user = await this.AuthService.login(email,password);

if(!user){
    return res.status(401).json({
        message: "login failed"
    });
}

req.session.userId = user.id;

res.json({
    message: "login success"
});

なのでレスポンス:

{
  "message": "login success"
}

になります。

image.png

6. セッションCookie確認(重要)

ログイン成功後、Postman上部のCookiesを選択します。

image.png

が存在すればOKです。

これがExpress-sessionのセッションIDです。

7. 次にTodo CRUD確認

ログイン後は、同じPostmanのウィンドウ(同じコレクション)で実行すれば、保存されたconnect.sidが自動送信されます。

Todo登録(Create)を確認します。

1. リクエスト作成

Method:

POST

URL:

http://localhost:3000/todos

2. Headers設定

通常は不要ですが、付けるなら:

image.png

3. Body設定

Body → raw → JSON

例:

{
  "title": "Express勉強",
  "completed": false
}

image.png

image.png

4. Send

成功すると、TodoのController実装次第ですが、例えば:

{
  "id": 1,
  "title": "Express勉強",
  "completed": false
}

のようなレスポンスになります。

5. セッションが送られているか確認

Postman上部のCookiesをクリック。

確認:

localhost
 └─ connect.sid

が残っている状態で実行してください。

ログイン後にこれがあるなら、Todo登録時に自動送信されます。

もし401 Unauthorizedになる場合

例:

{
  "message": "Unauthorized"
}

なら、authMiddleware が原因確認になります。

例えばよくある形:

AuthController.ts
export const authMiddleware = (
  req: Request,
  res: Response,
  next: NextFunction
) => {

  if(!req.session.userId){
    return res.status(401).json({
      message:"Unauthorized"
    });
  }

  next();
};

この場合、ログイン時に:

AuthController.ts
req.session.userId = user.id;

が保存されている必要があります。

確認順

Postmanではこの順番で実行します。

✅ POST /auth/register

http://localhost:3000/auth/register

✅ POST /auth/login

http://localhost:3000/auth/login


Cookiesに connect.sid

✅ POST /todos

http://localhost:3000/todos

Body:

{
  "title": "Express勉強",
  "completed": false
}

これでログインユーザーに紐づいたTodo登録確認になります。

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?