发布表单数据时请求正文为空

时间:2019-06-07 11:45:41

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

我正在向后端使用简单的发布请求以获取表单数据,并且由于某些原因,正文始终为空。 我试图将其隔离,因此我将内容类型更改为应用程序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();

})

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

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

与邮递员的行为相同。

5 个答案:

答案 0 :(得分:1)

您将需要从快递方面解析您的表单数据。为此,您将必须使用multer或multiparty。尝试这样的事情。还要参考文档

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);
       });
   });
})

答案 1 :(得分:1)

关于我的问题, 我有这个前端

 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中的表单甚至还需要一个括号{},即使它是一个对象。像这样

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

在那个后端有了这样的身体

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

答案 2 :(得分:0)

发布数据时,请求正文出现问题data type

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

祝你好运。

答案 3 :(得分:0)

您正在使用:

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()); 

答案 4 :(得分:-1)

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

但是我已经通过使用附加图像中突出显示的以下代码解决了这个问题:-

enter image description here

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

希望您使用上述代码片段解决您的问题。

相关问题