为什么在MERN堆栈中找不到我的POST路由



我目前在使用MERN堆栈应用程序时遇到两个问题:

i( 即使POST路由正常工作,Axios也没有将表单正文数据发送到服务器。每次提交后,都会创建一个新条目,但MongoDB只显示默认字段值

ii(我的POST路线最初是可行的,但现在已经不行了。现在似乎无法到达POST路由。我得到一个404未找到错误

网络应用程序有一个超级基本的功能来创建&列出学生&他们的数据通过表格&表。它使用组件模板的材料ui库

我的代码:

服务器-

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))

路线-

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

控制器-

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})

}

}

型号-

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

创建学生的表单-

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>
</>
);
}

提前感谢任何伸出援手的人!

您的中间件顺序错误:

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

JSON主体解析器安装在路由器之后。当请求到达路由处理程序时,req.body仍将是undefined,因为主体解析器尚未解析JSON请求主体。将JSON主体解析器移到路由器之前。

app.use(express.json(((应该在您的路由之上。因为当你发出post请求时,你需要处理json数据,它需要body解析器来解析json数据,所以只需将这一行放在所有路由之上即可。

最新更新