我现在通过mongoose将数据发送到mongodb,在获取它的api路由时,会抛出此错误
const addChoice = async (e) => {
try {
e.preventDefault();
const res = await fetch("/api/sendChoice", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
choiceSeq: choice,
checkSubmit: true,
}),
});
console.log(res);
router.push("/home");
} catch (error) {
console.log(error);
}
};
错误发生在const res = await fetch("/api/sendChoice" ,{
在终端服务器中显示错误
在inspect元素中,错误如下
我找不到任何与修复此问题相关的内容,我甚至不明白try 自己解决此问题意味着什么.
我的项目中的一些其他相关代码
import { getSession } from "next-auth/client";
import dbConnect from "../../helpers/dbConnect";
import Choice from "../../models/Choice";
export default async function sendChoice(req, res) {
try {
const session = await getSession({ req });
await dbConnect();
if (!session) {
res.status(401).send("You are not signed in");
return;
}
if (req.method === "POST") {
console.log(req.body);
const { choiceSeq, checkSubmit } = req.body;
console.log(choiceSeq, checkSubmit);
const userId = session.user.id;
const nameP = session.user.name;
const choice = new Choice({
user: userId,
name: nameP,
choiceSeq,
checkSubmit,
});
await choice.save();
res.status(200).send("Choice saved");
} else {
res.status(400).send("Bad request");
}
}
catch (error) {
console.log(error);
}
}
mongodb模式
import mongoose, { Schema } from 'mongoose';
const ChoiceSchema = new Schema({
user: {
type: Schema.Types.ObjectId,
ref: 'User',
},
name: {
type: String,
},
choiceSeq: {
type: Array,
default: [],
},
checkSubmit: {
type: Boolean,
}
});
mongoose.models = {};
export default mongoose.model('Choice', ChoiceSchema);