Home > OS >  Why is my POST route not found in MERN stack?
Why is my POST route not found in MERN stack?

Time:11-08

i'm currently having two problems with a MERN stack app:

i) Axios was not sending the form body data to the server even when the POST route was working. After each submission, a new entry is made but MongoDB only shows default field values

ii) My POST route was initially working but isn't anymore. Can't seem to hit a POST route now. I get a 404 Not Found error

The webapp has a super basic function to create & list students & their data via a form & table respectively. It uses the material-ui library for component templates

My code:

Server-

import express from 'express'
import cors from 'cors'
import mongoose from 'mongoose'
import dotenv from 'dotenv'
dotenv.config()
const app = express()
//ALWAYS use CORS middleware before defining ROUTES!
app.use(cors());
//import routes
import studentRoutes from './routes/student_routes.js'
//middleware to use routes 
app.use('/students' , studentRoutes)

app.use(express.json())
const URI = process.env.DB_URI
const port = process.env.PORT || 5000

mongoose.connect(URI, {
    useNewUrlParser: true, useUnifiedTopology: true
}).then( () => app.listen(port, () => 
console.log(`Listening on Port ${port}`)))
.catch( (err) => console.log(err))

Routes-

import express from 'express'
import { getStudents } from '../controllers/student_controller.js'
import { createStudent } from "../controllers/student_controller.js";

import Student from '../models/student_model.js'

const router = express.Router()


//list out all students
router.get('/', getStudents)
//adding new student
router.post('/', createStudent)

export default router

controller-

  import StudentData from '../models/student_model.js'
    
    export const getStudents = async (req, res) => {
        try {
        const allStudents = await StudentData.find()
        res.status(200).json(allStudents)
            
    } catch (err) {
    res.status(404).json( {message: err.message} )
    }};
    
    export const createStudent = async (req, res) => {
            const student = req.body
        const newStudent = new StudentData(student);
        try {
            await newStudent.save()
            res.status(201).json(newStudent)
            console.log('Student Created!')
        } catch (err) {
            res.status(404).json( {message: err.message})
            
        }
        
    }

model-

import mongoose from 'mongoose'

//model variable names must match the frontend useState's variables
const studentSchema = mongoose.Schema({
    regNo: Number,
    sutdentName: String,
    grade: String,
    section: {
        type: Number,
        default: 'A'
    },
    subjects: [String]

})

const StudentData = mongoose.model('StudentData', studentSchema)
export default StudentData

form to create student-

import * as React from "react";
import {useState} from 'react'
import Box from "@mui/material/Box";
import TextField from "@mui/material/TextField";
import Button from "@mui/material/Button";
import axios from 'axios'

export default function CreateStudent() {
    //state hook to dynamically update displayed data
    const [student, setStudent] = useState({
        regNo: '',
        studentName: '',
        grade: '',
        section: ''
    })

    //using axios to transfer data from front to backend
    const createStudent = () => {
        axios.post('http://localhost:5000/students', student)
        console.log(`  ${student.studentName}`)
    }
    return (
        
      <>
        <h2>Create New Student</h2>
        <Box
          component="form"
          sx={{
            "& > :not(style)": { m: 1, width: "25ch" },
          }}
          noValidate
          autoComplete="off"
        >
                <TextField id="outlined-basic" label="Registration No." variant="outlined" value={student.regNo} onChange={(event) => {
                    setStudent({ ...student, regNo: event.target.value })
                }} />
                <TextField id="outlined-basic" label="Name" variant="outlined" value={student.studentName} onChange={(event) => {
                    setStudent({ ...student, studentName: event.target.value })
                }} />
                <TextField id="outlined-basic" label="Grade" variant="outlined" value={student.grade} onChange={(event) => {
                    setStudent({ ...student, grade: event.target.value })
                }}/>
                <TextField id="outlined-basic" label="Class Section" variant="outlined" value={student.section} onChange={(event) => {
                    setStudent({ ...student, section: event.target.value })
                }}/>

          <Button variant="contained" onClick = {createStudent}>Submit</Button>
        </Box>
      </>
    );
}

Thank you in advance to anyone who lends a hand!

CodePudding user response:

Your middlewares are in the wrong order:

//middleware to use routes 
app.use('/students' , studentRoutes)

app.use(express.json())

The JSON body parser was mounted after the router. When a request reaches the route handler, the req.body will still be undefined because the body-parser has not parsed the JSON request body yet. Move the JSON body parser before the router.

  • Related