React:将 FormData 发送到服务器 returns {}
React: sending FormData to the server returns {}
我有一些要提取到 post url.
的 FormData
const data = new FormData(e.currentTarget); //form currentTarget
data.set("file", file)
data.append("description", editorState.blocks[0].text)
e.preventDefault();
await fetch(process.env.NEXT_PUBLIC_DR_HOST, { //http://localhost:3000/
method: 'POST',
body: data,
}).then(res =>
{
console.log(res)
// window.location = res.url;
})
发送数据后,console.log(req.body)
我得到了return{},console.log(req.body.get("file") //or anything else instead of file)
return什么都没有。
server.js 中间件:
server.use(express.urlencoded({ extended: true }));
server.use(express.static(path.join(__dirname, 'assets')));
我尝试了多种解决方案,但最终结果还是一样{}。我该如何解决这个问题?
反应组件:
e.preventDefault();
const data = new FormData(e.currentTarget);
data.append("file", JSON.stringify(file))
data.append("description", JSON.stringify(editorState))
await fetch(process.env.NEXT_PUBLIC_DR_HOST, {
method: 'POST',
body: body,
// headers: { 'Content-Type': 'multipart/form-data' }
}).then(res =>
{
// window.location = res.url;
})
控制器:
router.post('/', upload.single('file'), async (req, res, next) =>
{
//rest of the stuff
忘记在具体功能前加上multer upload中间件
我有一些要提取到 post url.
的 FormDataconst data = new FormData(e.currentTarget); //form currentTarget
data.set("file", file)
data.append("description", editorState.blocks[0].text)
e.preventDefault();
await fetch(process.env.NEXT_PUBLIC_DR_HOST, { //http://localhost:3000/
method: 'POST',
body: data,
}).then(res =>
{
console.log(res)
// window.location = res.url;
})
发送数据后,console.log(req.body)
我得到了return{},console.log(req.body.get("file") //or anything else instead of file)
return什么都没有。
server.js 中间件:
server.use(express.urlencoded({ extended: true }));
server.use(express.static(path.join(__dirname, 'assets')));
我尝试了多种解决方案,但最终结果还是一样{}。我该如何解决这个问题?
反应组件:
e.preventDefault();
const data = new FormData(e.currentTarget);
data.append("file", JSON.stringify(file))
data.append("description", JSON.stringify(editorState))
await fetch(process.env.NEXT_PUBLIC_DR_HOST, {
method: 'POST',
body: body,
// headers: { 'Content-Type': 'multipart/form-data' }
}).then(res =>
{
// window.location = res.url;
})
控制器:
router.post('/', upload.single('file'), async (req, res, next) =>
{
//rest of the stuff
忘记在具体功能前加上multer upload中间件