Home > Mobile >  NodeJS Express: Server cannot resolve GET, PUT, POST, or DELETE requests (Status 404)
NodeJS Express: Server cannot resolve GET, PUT, POST, or DELETE requests (Status 404)

Time:07-15

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.

CodePudding user response:

You've registered all your controllers as error handling middleware.

Define error-handling middleware functions in the same way as other middleware functions, except error-handling functions have four arguments instead of three: (err, req, res, next)

Remove the first err parameters from each of them

const createGoal = (req, res, next) => {
  res.json({message: "Create goal"})
}

const getGoals = (req, res, next) => {
  res.json({message: "Read goals"})
}

const updateGoal = (req, res, next) => {
  res.json({message: `Update this goal: ${req.params.id}`})
}

const deleteGoal = (req, res, next) => {
  res.json({message: `Delete this goal: ${req.params.id}`})
}

FYI, the default response status when using res.json() is 200.

CodePudding user response:

You have to try this one in goalRoutes.js file

router.use('/').post(createGoal).get(getGoals)
router.use('/:id').put(updateGoal).delete(deleteGoal)

CodePudding user response:

if you use nodejs module import try implementing this into your code, it works

export default ()=> {
    const app = Router()

    RolesRoute(app)
    auth(app)
    FlightRoute(app)
    MaintenanceRoute(app)
    Books(app)

    app.use('/user',UserRoute())

    app.use('/engineer', EngineerRoute())
    app.use('/instructor', InstructorRoute())

    return app
}

Auth Routes



import { Router } from 'express'

import {AuthValidator} from "../../../lib/validator";
import AuthController from "../../../controllers/auth.controller";
import {isAdmin, isAuth} from "../../../lib/middleware/auth";

const route = Router();
export default (app)=> {
    app.use('/auth', route);

    /**
     * Sign in
     */
    route.post("/signIn", AuthValidator.signInValidator, AuthController.signIn)

}
  • Related