首页 > 解决方案 > React 中的 Axios 请求问题

问题描述

我正在尝试使用 React 框架从前到后启动发布 Axios 请求。当我使用我的本地主机服务器时,它可以工作,但我使用 Heroku 地址时,我的控制台中有一条错误消息(400 错误请求)。我尝试使用 heroku 启动其他 get Axios 请求并且它有效。所以我想知道我遇到的问题与 Post Axios 请求有关。我会很感激你的评论

请在下面找到我的代码(正面反应):

import React from "react";

import axios from "axios";

const Questions = () => {
  const fetchData = async () => {
    const response = await axios.post(
      "https://formnest-back-certification.herokuapp.com/form/create",
      {
        title: "nouveau formulaire",
      }
    );

    console.log(response.data);
  };

  fetchData();

  return (
    <>
      <div>Hello form</div>
    </>
  );
};
export default Questions;

这是我在 React 后面的代码:

router.post("/form/create", async (req, res) => {
  try {
    /* const titleForm = await Form.findOne({ title: req.fields.title });
    console.log(titleForm);

    if (titleForm) {
      return res.status(400).json({ error: "title already used" });
    } else { */
    if (req.fields.title) {
      const newForm = new Form({
        title: req.fields.title,
        /* questions: req.fields.questions,
          answers: req.fields.answers, */
      });

      // Sauvegarde du formulaire
      await newForm.save();
      return res.json(newForm);
    } else {
      return res.status(400).json({ error: "Missing parameters" });
    }
  } catch (e) {
    return res.status(400).json({ error: e.message });
  }
  /*  console.log(req.fields); */
  /* 
  res.json({ message: "form created" }); */
});

在我发布 axios 请求之后的控制台屏幕截图

标签: javascriptreactjsherokuaxios

解决方案


如果您对 POST 请求使用 express 框架,则需要使用body-parser模块然后使用req.body来检索请求数据。

req.fields 是当您使用express-formidable模块时。


推荐阅读