node.js - 如何在 MERN 堆栈应用程序中发送多个数据?
问题描述
我需要帮助才能发布有关类别的多个数据,当我在选择输入上选择多个数据并提交时会引发错误。请参阅下面的错误
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 发布请求正在向http://localhost:5000/posts发出,但是,您的服务器代码中似乎没有“/posts”路由。尝试更改您的服务器代码以在“/posts”处接受发布请求。见下文:
router.post("/", upload.single("blogImage"), async (req, res) => {
// vs
router.post("/posts", upload.single("blogImage"), async (req, res) => {
或者,您可以从您的 axios 请求中删除帖子路由,并向http://localhost:5000发出请求。
推荐阅读
- c# - 为什么视图没有从 SQL Server 更新数据
- c# - 将矩阵的选定元素返回到
- java - 使用 springboot 调度程序创建动态 cron 作业
- python - 逻辑回归与通过将数据拆分为 bin 来预测概率
- sql - 同时预订
- api - 尝试访问 api 时 GET 500(内部服务器错误)
- python - 有没有办法从 SQLAlchemy / FastAPI 关系中返回两个字段?
- macos - 在 MacOS 上的 zsh 终端中穿梭:“预期的服务器初始化字符串 b'SSHUTTLE0001';得到 b''”
- swift - 在 Xcode/Swift 中实现替换和插入按钮
- c# - 如何在 TFS 2015 中增加测试代理的屏幕分辨率