I have no idea what the heck is happening anymore. The routes were working perfectly without touching the code, and then it all broke. Now only the POST works, but the DELETE gives me an unauthorized. I am passing the token through the state and sometimes gets
or jwt not provided.
import { Router } from 'express'
const router = Router()
import knex from '../../knex'
import { verify } from 'jsonwebtoken'
import {} from ('dotenv').config()
// Middleware to check token in header
const jwtVerify = (req, res, next) => {
verify(req.headers.token, process.env.PASSWORD, (err, _payload) => {
if (err) {
err.status = 401
err.message = `Unauthorized - You are not Chizette!`
return next(err);
} else {
req.payload = _payload
next()
}
})
}
// Middleware to check ID
const checkIdisNum = (req, res, next) => {
if (isNaN(req.params.id)) {
let err = new Error(`Id not found`)
err.status = 400
throw err
}
next()
}
// Read all records in DB
router.get('/', (req, res, next) => {
knex('chizetteart')
.orderBy('updated_at', 'desc')
.orderBy('id')
.then((rows) => {
res.json(rows)
})
.catch((err) => {
next(err)
})
})
// Get one record in DB
router.get('/:id', checkIdisNum, (req, res, next) => {
knex('chizetteart')
.where('id',req.params.id)
.then((rows) => {
res.json(rows)
})
.catch((err) => {
next(err)
})
})
// Create one record and post to DB
router.post('/', jwtVerify, (req, res, next) => {
knex('chizetteart')
.insert({
"title": req.body.title,
"year": req.body.year,
"medium": req.body.medium,
"poster": req.body.poster,
"price": req.body.price
})
.returning('*')
.then((data) => {
res.json(data[0])
})
.catch((err) => {
next(err)
})
})
// Edit one record in DB
router.put('/:id', jwtVerify, checkIdisNum, (req, res, next) => {
knex('chizetteart')
.where('id', req.params.id)
.then((data) => {
knex('chizetteart')
.where('id', req.params.id)
.limit(1)
.update({
"title": req.body.title,
"year": req.body.year,
"medium": req.body.medium,
"poster": req.body.poster,
"price": req.body.price
})
.returning('*')
.then((data) => {
res.json(data[0])
})
})
.catch((err) => {
next(err)
})
})
// Delete one record
router.delete('/:id', jwtVerify, checkIdisNum, (req, res, next) => {
knex('chizetteart')
.where('id', req.params.id)
.first()
.then((row) => {
if(!row) return next()
knex('chizetteart')
.del()
.where('id', req.params.id)
.then(() => {
res.send(`ID ${req.params.id} Deleted`)
})
})
.catch((err) => {
next(err)
})
})
export default router
I never touched the code. I’m ready to throw my computer out the window.