【问题标题】:Request body is empty when posting form-data发布表单数据时请求正文为空
【发布时间】:2019-10-22 22:12:09
【问题描述】:

我正在对我的后端使用一个简单的发布请求来获取表单数据,但由于某种原因,正文总是空的。 我试图隔离这一点,所以我将内容类型更改为应用程序 json 并将数据更改为 json,只有这样我才能发送数据。

客户端:

submitForm(event) {
        event.preventDefault();
        console.log("gggg");
        const data = new FormData(event.target);

         axios.post("http://localhost:4000/user-form-post",data).then(function (response) {
            //handle success
            console.log(response);
        })
        .catch(function (response) {
            //handle error
            console.log(response);
        });

服务器端:

// app.use(bodyParser.json());
// app.use(bodyParser.urlencoded({extended:true}));

app.use(express.urlencoded());

// Parse JSON bodies (as sent by API clients)
app.use(express.json());

app.use(logger('dev'));
app.post('/user-form-post', (req,res) =>{

    console.log("dfdf");
    console.log(req.body); // alwayes print empty dict {}
    res.end();

})

这不起作用,因为它需要 jsons(预期行为):

// app.use(bodyParser.json());
// app.use(bodyParser.urlencoded({extended:true}));

与 Postman 的行为相同。

【问题讨论】:

标签: node.js express client backend body-parser


【解决方案1】:

您需要从 express 端解析表单数据。为此,您将不得不使用 multer 或多方。尝试这样的事情。参考文档

const multiparty = require('multiparty');

app.post('/user-form-post', (req,res) =>{

   let form = new multiparty.Form();

   form.parse(req, function(err, fields, files) {
      Object.keys(fields).forEach(function(name) {
           console.log('got field named ' + name);
       });
   });
})

【讨论】:

  • 你能详细说明一下为什么 req.body 是空的吗?
  • @KaramJaber 这是因为您是从前端发送表单数据,而 express 无法解析表单数据。为此,您将不得不使用某种能够解析表单数据的中间件。最著名的中间件是 multer 和 multiparty。
  • @TRomesh 为什么 Express 不能处理如此常见的用例?图书馆是 100% 必要的吗?
【解决方案2】:

当谈到我的问题时, 我有这个前端

 const form = new FormData();
      form.email = this.email;
      form.password = this.password;
      console.log("onSubmit -> form", form);

axios.post("http://localhost:3000/register",  form )

onSubmit -> form FormData {email: "admin@gmail.com", password: "123"}

但是后端的 req.body 是空的,我发现 axios.post 中的表单仍然需要 1 个括号 {},即使它是一个对象。像这样

axios.post("http://localhost:3000/register", { form })

在后端得到这样的身体之后

req.body = { form: { email: 'admin@gmail.com', password: '123' } }

【讨论】:

    【解决方案3】:

    发布数据时请求正文的问题是data type。

    我最近遇到了 Postman 的问题。 您应该发布类型为x-www-form-urlencoded 或raw->JSON 的数据来解决问题。

    祝你好运。

    【讨论】:

      【解决方案4】:

      您正在使用:

      app.use( bodyParser.json() );  // to support JSON-encoded bodies
      app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
        extended: true
      }));
      

      请也使用下面给出的行代码,但首先安装 multer 并在应用程序顶部编写代码:

      var multer = require('multer');
      var upload = multer();
      
      app.use(express.json()); 
      

      【讨论】:

        【解决方案5】:

        我在发布的代码中也遇到了同样的问题。

        但我已使用附图中突出显示的以下代码解决了此问题:-

        enter image description here

        没有使用 “Content-Type” 来解决此问题。

        希望您使用上面的代码 sn-ps 解决您的问题。

        【讨论】:

        • 建议用户在答案本身中提供代码sn-ps,而不是链接到外部资源。图片中的代码可以添加到代码 sn-p 中的答案中。
        猜你喜欢
        • 2022-01-11
        • 2021-08-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-05-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多