【问题标题】:Cannot get the request body in the Backend无法在后端获取请求正文
【发布时间】:2023-01-19 21:51:30
【问题描述】:

我创建了一个 FormData 对象并附加了两个字段 audioemail。当我使用 axios 发送请求时,我无法在后端接收请求正文。

const email = 'my@gmail';
const url = 'http://';

const sendData = () =>{

 let fd = new FormData();

 const audio = new Blob(audioData, { type: "audio/ogg; codecs=opus" });

 fd.append('audio' , audio);
 fd.append('email', email);

 const resp =  await axios.post(url, fd);
 

后端方面。


// First middleware 

const { User } = require("../models/userSchema");

module.exports = async function (req, res, next) {

    console.log(req.body); // {}

    next();

};

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    您需要使用 'Content-Type': 'multipart/form-data'~ 标头。

    const sendData = () =>{
     let fd = new FormData();
     const audio = new Blob(audioData, { type: "audio/ogg; codecs=opus" });
     fd.append('audio' , audio);
     fd.append('email', email);
    
     const resp =  await axios.post(url, fd, {
       headers: {
         'Content-Type': 'multipart/form-data'
       }
     });
     console.log(resp);
    
    

    【讨论】:

    • 我已经放了标题,但我仍然在 API 端得到一个空对象 {}
    • 看起来您没有解析 multipart/form-data 内容。由于body-parser 不解析多部分数据。请考虑为此使用 multer npm 模块。
    猜你喜欢
    • 2015-10-15
    • 2016-08-01
    • 2020-11-04
    • 1970-01-01
    • 1970-01-01
    • 2020-05-16
    • 2022-01-17
    • 2021-08-30
    • 1970-01-01
    相关资源
    最近更新 更多