目前我正在尝试学习MERN堆栈,但我很难让它运行。我总是遇到404错误,但是,经过几个小时的研究,我无法修复它。我很感激你的帮助。
服务器/index.js
import express from "express";
import mongoose from "mongoose";
import cors from "cors";
import usersRoutes from "./routes/users.route.js";
const app = express();
app.use(cors());
app.use("/users", usersRoutes);
const CONNECTION_URL =
"mongodb+srv://...";
const PORT = process.env.PORT || 3001;
mongoose.connect(CONNECTION_URL);
app.listen(PORT, () => {
console.log(`Server running on Port: http://localhost:${PORT}`);
});
服务器/线路/users.route.js
import express from "express";
import UserModel from "../models/Users.js";
const router = express.Router();
router.get("/getUsers", (req, res) => {
UserModel.find({}, (err, result) => {
if (err) {
res.json(err);
} else {
res.json(result);
}
});
});
export default router;
服务器/模型/Users.js
import mongoose from "mongoose";
const UserSchema = new mongoose.Schema({
name: {
type: String,
required: true,
},
age: {
type: Number,
required: true,
},
username: {
type: String,
required: true,
},
});
const UserModel = mongoose.model("users", UserSchema);
export default UserModel;
您正在"安装"。你的路由器在这里:
app.use("/users", usersRoutes);
这将匹配以/users
为前缀的请求。
然后声明一个路由:
router.get("/getUsers", (req, res) => { … })
由于前缀的关系,这条路由的URL将是/users/getUsers
。
如果您希望URL为/getUsers
,则省略前缀:
app.use(usersRoutes);