gpt4 book ai didi

javascript - 尝试获取 request.body Nodejs 中的所有字段时出现异常 "Object.keys called on non-object while trying to access object"?

转载 作者:搜寻专家 更新时间:2023-11-01 00:43:25 24 4
gpt4 key购买 nike

我有一段这样的 PUT 方法的代码

module.exports.addRoutes = function(server) {
//PUT
server.put('/api/public/place/:id', function(request, response) {
//this is just for testing, please do not care about the id
var placedetail = request.body;
for(var key in placedetail)
{
console.log(placedetail[key]);
}
});
};

在这段代码中,我想获取所有的请求体字段,如request.body.name,request.body.email等。字段参数由用户决定,服务器将通过key获取值.

比如用户把数据放在请求中

{
name:"Test"
email:"abc@gmail.com"
}

另一个用户把数据放成这样

    {
address:"Test"
location:"Some Test String"
}

我使用这种方式并得到异常“Object.keys called on non-object while trying to access object”。但是在访问各个字段的时候,比如:request.body.name, request.body.email,还是可以成功获取到参数。

我也给你另一种方法,通过JSON.parse(request.body.toString())来解析数据,但实际上,数据不是JSON,无法解析。

如何获取request.body的所有字段?

谢谢。

最佳答案

您可以使用 body-parser解析 req.body 数据的模块:

var bodyParser = require('body-parser');

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

关于javascript - 尝试获取 request.body Nodejs 中的所有字段时出现异常 "Object.keys called on non-object while trying to access object"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26910995/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com