为什么在 MERN 堆栈中找不到我的 POST 路由?
Why is my POST route not found in MERN stack?
我目前在使用 MERN 堆栈应用程序时遇到两个问题:
i) 即使 POST 路由有效,Axios 也没有将表单主体数据发送到服务器。每次提交后,都会创建一个新条目,但 MongoDB 仅显示默认字段值
ii) 我的 POST 路线最初有效,但现在无效了。现在似乎无法到达 POST 路线。我收到 404 未找到错误
Web 应用程序有一个超级基本的功能,可以分别通过表单和 table 创建和列出学生及其数据。它使用 material-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 数据并且它需要
正文解析器解析 json 数据,所以只需将该行置于所有路由之上。
我目前在使用 MERN 堆栈应用程序时遇到两个问题:
i) 即使 POST 路由有效,Axios 也没有将表单主体数据发送到服务器。每次提交后,都会创建一个新条目,但 MongoDB 仅显示默认字段值
ii) 我的 POST 路线最初有效,但现在无效了。现在似乎无法到达 POST 路线。我收到 404 未找到错误
Web 应用程序有一个超级基本的功能,可以分别通过表单和 table 创建和列出学生及其数据。它使用 material-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 数据并且它需要 正文解析器解析 json 数据,所以只需将该行置于所有路由之上。