server.js
const express = require('express')
const dotenv = require('dotenv').config()
const port = process.env.PORT ||9999
const goals = require('./routes/goalRoutes')
const app = express()
app.use('/api/goals', goals)
app.listen(port, () => console.log(`Server started on port ${port}`))
goalRoutes.js defines a route api/goals
const express = require('express')
const router = express.Router()
const { createGoal, getGoals, updateGoal, deleteGoal, } = require('../controllers/goalController')
router.route('/').post(createGoal).get(getGoals)
router.route('/:id').put(updateGoal).delete(deleteGoal)
module.exports = router
goalController.js gives functionality to that route
//@desc Create goal
//@route POST /api/goals
//@access Private
const createGoal = (err, req, res, next) => {
res.status(200).json({message: "Create goal"})
}
//@desc Get goals
//@route GET /api/goals
//@access Private
const getGoals = (err, req, res, next) => {
res.status(200).json({message: "Read goals"})
}
//@desc Update goal
//@route PUT /api/goals:id
//@access Private
const updateGoal = (err, req, res, next) => {
res.status(200).json({message: `Update this goal: ${req.params.id}`})
}
//@desc Get goals
//@route DELETE /api/goal/:id
//@access Private
const deleteGoal = (err, req, res, next) => {
res.status(200).json({message: `Delete this goal: ${req.params.id}`})
}
module.exports = {
createGoal,
getGoals,
updateGoal,
deleteGoal,
}
I have created a route (intended as /api/goals) and controllers for that route. I then used the controllers found in goalController.js to handle GET, PUT, POST, and DELETE requests and connected that to goalRoutes.js.
Using Postman for testing, I can only resolve these requests with a 404 status.
My initial thought process was that I didn't correctly import the controller functions into goalRoutes.js, but I seem to have exported them as an object just fine and Node doesn't seem to have an issue with anything at runtime.
I used to have the body of the controllers' functions within the callback functions of router.get, router.post, router.put, and router.delete but that was really messy. I would strongly prefer not to go back to that mess.
I am at a loss. What's stopping the callback functions of router.route to use the controller functions? Why does Postman receive 404?
I apologize if my terminology sucks. I'm a total beginner at Javascript.