javascript - 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" }); */
});
解决方案
如果您对 POST 请求使用 express 框架,则需要使用body-parser
模块然后使用req.body
来检索请求数据。
req.fields 是当您使用express-formidable
模块时。
推荐阅读
- reactjs - Reactjs - div的背景图像不起作用
- python - 自定义对象训练张量流错误
- javascript - Javascript 解密 C# AES 加密
- angular - 角度 5 中的发布错误 请求的资源上不存在“Access-Control-Allow-Origin”标头。
- c# - 在 ListBox 中显示所有正在运行的应用程序并在 c# 中单击按钮时将其杀死
- python - 根据用户输入在多行中制作带有 x 和空格的图片
- java - 使用 ArrayList 进行合并排序
- c++ - 有没有办法使用初始化到第一行的指针来访问二维数组的第二行?
- javascript - 为什么我的 Jquery 自动完成功能不适用于 Mysql 数据
- json - 如何使用rest API和spring boot解析JSON文件