如何在MERN堆栈应用程序中发送多个数据?

时间:2020-04-23 05:46:10

标签: node.js reactjs mongodb 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)

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

1 个答案:

答案 0 :(得分:0)

您收到400错误。好像是向http://localhost:5000/posts发出了axios发布请求,但是,在服务器代码中似乎没有“ / posts”路由。尝试更改服务器代码以在“ / posts”接受发布请求。见下文:

router.post("/", upload.single("blogImage"), async (req, res) => {

// vs 

router.post("/posts", upload.single("blogImage"), async (req, res) => {

或者,您可以从axios请求中删除帖子路线,然后向http://localhost:5000发出请求。