🌊
JWT Authentication【1auth route】
JWT Authentication【1auth route】
YouTube: https://youtu.be/6b55_OLSP0Y
Backend 前回の動画シリーズ: https://youtu.be/YofQ3enYF0s
auth.ts
import { Router } from "express";
import { register } from "../controllers/authControllers";
const router = Router()
router.post('/register', register)
export default router
authControllers.ts
import {Request, Response} from 'express'
import { prisma } from '../utils/prismaClient'
export const register = async (req: Request, res: Response) => {
const {email, name, password, confirm_password} = req.body
if (password !== confirm_password ) {
res.status(400).json({
'message': "Password do not match confirm password."
})
return
}
try {
const user = await prisma.user.create({
data: {
email: email,
name: name,
password: password
},
select: {
id: true,
email: true,
name: true,
}
})
res.status(200).json(user)
} catch (error) {
res.status(500).json({"error": error})
}
}
index.ts
import express from 'express'
import helmet from 'helmet'
import morgan from 'morgan'
import cors from 'cors'
import userRoute from './routes/user'
import postRoute from './routes/post'
import authRoute from './routes/auth'
const app = express()
const port = 4000
app.use(express.json())
app.use(express.urlencoded({extended: true}))
app.use(cors())
app.use(helmet())
app.use(morgan('common'))
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.use('/api/users', userRoute)
app.use('/api/posts', postRoute)
app.use('/api/auth', authRoute)
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
Discussion