我需要帮助在类别上发布多个数据,当我在选择输入上选择多个数据并提交时,它会抛出错误。请参阅下面的错误
setSelected = (selected) => {
this.setState({ selected });
};
handleSubmitPost = (e) => {
const selected = this.state.selected;
let select = [];
for (let i = 0; i < selected.length; i++) {
select = [...select, selected[i].value];
}
console.log(select);
e.preventDefault();
const fd = new FormData();
fd.append("title", this.state.title);
fd.append("category", select);
fd.append("article", this.state.article);
fd.append("blogImage", this.state.blogImage);
axios
.post(`http://localhost:5000/posts`, fd)
.then((res) => {
console.log(res);
})
.catch((err) => console.log(err));
};
下面是模型模式。模型
const postSchema = new mongoose.Schema({
title: { type: String, required: true },
category: [
{
type: Schema.Types.ObjectId,
ref: "PostCategory",
},
],
article: { type: String, required: true },
blogImage: { type: String, required: true },
createdAt: { type: Date, default: Date.now },
});
这是我的路线文件。路线
router.post("/", upload.single("blogImage"), async (req, res) => {
const { title, article, createdAt, category } = req.body;
const newPost = new Post({
title,
category,
article,
createdAt,
blogImage: req.file.path,
});
try {
const savedPost = await newPost.save();
res.json(savedPost);
} catch (err) {
res.status(400).send(err);
}
});
当我在输入选择上选择多个时,这是我提交时的错误。
Error: Request failed with status code 400
at createError (createError.js:16)
at settle (settle.js:17)
at XMLHttpRequest.handleLoad (xhr.js:61)
但当我只选择一个时,它就会通过。我只能保存一个在五月类别字段,我想保存多个在我的类别字段。
您将得到一个400的错误。看起来axios post请求是向http://localhost:5000/posts发出的,但是,服务器代码中似乎没有“/posts”路由。尝试更改服务器代码以接受“/posts”处的post请求。见下文:
router.post("/", upload.single("blogImage"), async (req, res) => {
// vs
router.post("/posts", upload.single("blogImage"), async (req, res) => {
或者,您可以从axios请求中删除posts路由,并向http://localhost:5000发出请求。