I've set up a basic code structure to test my routes, but I keep getting a 404 error. Although I have an app.all function to catch errors, I'm having trouble pinpointing where the issue lies.
Below is my index.js file, where I've configured my express server and included the error catching app.all function:
const express = require('express')
const cors = require('cors')
const app = express()
const PORT = process.env.PORT || 8000
app.use(cors())
app.use(express.urlencoded({ extended: true }))
const userRoutes = require('./routes/users.js')
app.get('/', (req, res) => {
res.send('Backend is up')
})
app.use('/', userRoutes)
app.all('*', (req, res,) => res.send('That route does not exist!'))
app.listen(PORT, () => console.log(`Server running on port ${PORT}`))
Here's my routes file, where I retrieve data from the users file:
const express = require('express');
const { getUsers, createUser, deleteUser } = require('../controllers/users.js')
const router = express.Router();
router.get('/users', getUsers)
router.post('/user', createUser)
module.exports = router;
Finally, here's my users file inside the controllers folder, where I handle setting up data for the client side:
const {v4 : uuidv4} = require('uuid')
let users = []
exports.getUsers = (req, res) => {
try {
res.send(users)
} catch (error) {
console.error(error)
}
}
exports.createUser = (req, res) => {
try {
const user = req.body
users.push({...user, id: uuidv4()})
res.send("User Added Successfully!")
} catch (error) {
console.error(error)
}
}