【问题标题】:Express.Js: Get value from object that key value is string valueExpress.Js:从键值为字符串值的对象中获取值
【发布时间】:2021-02-04 02:12:57
【问题描述】:

我很好奇从键值是字符串的对象中获取值的正确方法。 来自客户端的数据发布并从 express.Js 后端的 req.body 接收。

从客户端。例如

var waypoints = {lat:15,lng:16};
$.ajax({
type:"POST",
url:'someurl',
data: { routeId:someId,origin: origin, waypoints::waypoints, destination: finaldestination.lat+','+finaldestination.lng,}
});

console.log 来自从 express.js 后端接收的数据。例如

{
 routeId:'1234',
 origin:'1.123,2.234',
 'waypoints[lat]':'15',
 'waypoints[lng]':'16',
 destination:'3.123,3.234,
}

console.log(req.body.waypoints); //未定义

我尝试将waypoint 从客户端更改为字符串。 例如。

var waypoints '';
waypoints += '15,16';

此方法效果很好,从 express.js 后端中的req.body.waypoints 获取值。

{
origin:'1.123,2.234',
waypoint:'15,16',
destination:'3.123,3.234'
}

这里的问题是我究竟如何从'waypoints[lat]''waypoints[lng]' 获得值?

【问题讨论】:

  • 使用data: JSON.stringify({ ... })发送JSON;这样 express 应该将请求正文解析回一个完整的对象。 (我想知道[0] 是从哪里来的,因为你的data.waypoint 中没有数组。为什么有两个冒号?)
  • 我猜如果你为数据传递一个对象,jquery会做自己的字符串化,这将使一个数组作为航点[0].....
  • @ChrisG 感谢您的回答,我会在上面尝试您的建议。 [0] 是我的错误,原来 waypoint 是一个通过 for 循环添加对象的数组。所以应该是'waypoints[lat]': and 'waypoints[lng]': 编辑消除误会。
  • 试试req.body['waypoints[lat]']
  • @ChrisG 我已经尝试过你的建议,这样我可以将多个值与数组一起发送到航路点。例如waypoints: JSON.stringify(allwaypoints),以后更容易获得一组lan&lng。非常感谢您的帮助:D

标签: javascript node.js express


【解决方案1】:

您会注意到航点的键是一个字符串,因为它使用的字符通常与 javascript 对象的键不兼容([])。

因此,要访问它们,您可以使用方括号而不是点符号

var data = {
 routeId:'1234',
 origin:'1.123,2.234',
 'waypoints[lat]':'15',
 'waypoints[lng]':'16',
 destination:'3.123,3.234'
};

console.log(data.routeId); // this works fine
console.log(data['waypoints[lat]']) // square bracket notation needed
console.log(data.waypoints[lat]); // this assumes a property waypoints and thinks you;re trying to read a property on it stored in variable "lat" which is not defined

【讨论】:

  • 谢谢,你的解释真的很解释,也解开了我的误解。感谢您的帮助和时间:D。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-10-19
  • 2012-11-30
  • 2016-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-24
相关资源
最近更新 更多