简体   繁体   English

表达:无法通过request.body.paramName直接访问参数

[英]express: parameters are not directly accessible through request.body.paramName

I am trying to submit a form from an angular app: 我正在尝试通过有角度的应用程序提交表单:

 var formdata={
         date:$scope.myForm.date
        ,name:$scope.myForm.name
        ,mobile:$scope.myForm.phone
    };

$http({
        method:"POST"
        ,url:'/forms/submit'
        ,data:formdata
        , headers:{'Content-type':"application/x-www-form-urlencoded; charset=utf-8"}
    })

But when I request it with request.body.date , I am getting undefined. 但是当我使用request.body.date ,我变得不确定。 Printing request.body the parameters are passed though. 打印request.body参数虽然通过。

Listening on port 3000
'----   submitForm -----'
{ '{"date":"20140630","name":"asdf","phone":"12312"}': '' }

The server code uses body-parser : 服务器代码使用body-parser

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

When I print request.body.name I am getting undefined , but it is in there as you saw. 当我打印request.body.name我得到的是undefined ,但是如您所见,它在那里。 What am I doing wrong? 我究竟做错了什么?

You need to convert formdata to a urlencoded string first, otherwise it gets serialized as JSON instead (by $http). 您需要formdata转换为urlencoded字符串,否则它将序列化为JSON(由$ http代替)。 That's why you see JSON on the server side currently. 这就是为什么您当前在服务器端看到JSON的原因。

If you already have jQuery on the page, you can convert the formdata object via $.param(formdata) and use that as your data value instead. 如果页面上已经有了jQuery,则可以通过$.param(formdata)转换formdata对象,并将其用作data值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM