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?

TypeExpressTutorial - 4

Last updated at Posted at 2024-07-05

やりたいこと

  • /api/auth/signupGET でリクエストされたら任意のJSONが返却されるAPIを作る
  • /api/auth/loginGET でリクエストされたら任意のJSONが返却されるAPIを作る

全体像

処理の順番

  1. リクエストを routes層 で受け取る
  2. routes層 で実際の処理の関数をコールする
  3. 処理の関数は controller層 で記述する
  4. signup関数, login関数 がコールされたら任意の JSON が返却される

Controller

src/controllers/auth.ts ファイルを新規で作成する

src/controllers/auth.ts
import { Request, Response } from 'express'

export const signup = async (req: Request, res: Response) => {
  res.json({ message: 'Signup route' })
}

export const login = async (req: Request, res: Response) => {
  res.json({ message: 'Login route' })
}

Routes

src/routes/auth.ts ファイルを新規で作成する

src/routes/auth.ts
import { Router } from 'express'
import { login, signup } from '../controllers/auth'

const authRouter: Router = Router()

authRouter.get('/signup', signup)
authRouter.get('/login', login)

export default authRouter

src/routes/index.ts ファイルを新規で作成する

src/routes/index.ts
import { Router } from 'express'
import authRouter from './auth'

const rootRouter: Router = Router()

rootRouter.use('/auth', authRouter)

export default rootRouter

エントリーファイル(index.ts)への記述

src/index.ts ファイルに追記

src/routes/index.ts
import express, { Express, Request, Response } from 'express'

import { PORT } from './secrets'
import rootRouter from './routes' // <- 追記

const app: Express = express()

app.use(express.json()) // <- 追記
app.use('/api', rootRouter) // <- 追記

app.listen(PORT, () => {
  console.log('Server is running on http://localhost:8000')
})
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?