React, node js, mongoDB - 如何使用 FormData 进行发布、放置、删除?



如何使用表单数据创建邮政服务?

我通过Axios发送了表单数据。 但是,node-express 服务器上的 'req.body.title' 值为空。 所以现在我以以下格式发送提取。 但是我需要将文件上传到服务器,所以我想使用 formData 发送它。

let bodys = 'title=a1&contents=b'
fetch("http://localhost:5000/test", {
method : 'post',
headers : {
'Content-type' : 'application/x-www-form-urlencoded; charset=UTF-8'
},
body: bodys
})
.then(function(response){
console.log('Request Succeded ', response);
})
.catch(function (error){
console.log('Failed ', error)
})

我使用附加新的 FormData(( 编写了新数据, 我检查了 FormData 是否包含 React 上的值。 但是,节点快速服务器没有进入正文。

请让我知道该怎么做...

尝试发送 FormData 对象而不是原始字符串作为请求正文。

const bodys = new FormData();
bodys.append('title', 'a1');
bodys.append('contents', 'b');

此表单数据将在 express.js 服务器的 request.body 中提供。

编辑:要在express.js中解析FormData,您需要像multer这样的中间件

const upload = require('multer');
app.use('/', upload.any(), yourRouteHandler);

你只发送一个字符串,所以

您可以像下面这样访问您的身体

let bodys = 'title=a1&contents=b'
console.log(req.body); //will print title and contents as you are sending

如果要分别访问标题和内容,则必须将数据作为对象发送

const bodys = {“title”: “a1”, “contents”: “b”}
console.log(“title”, req.body.title); //will print a1
console.log(“contents”, req.body.contents); //will print b

切切此线程以获取更多详细信息 https://github.com/github/fetch/issues/263

最新更新