首页 > 解决方案 > 如何在 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)

但是当我只选择一个时它通过了。我只能在可能的类别字段中保存一个,而我想在我的类别字段中保存多个。

标签: node.jsreactjsmongodbmern

解决方案


您收到 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发出请求。


推荐阅读