为何使用JavaScript Traverson HAL $all元选择器返回空数组?
问题原因与解决方案
原因
你误用了$all元选择器的使用场景。根据Traverson HAL的规则,$all是用来提取当前请求到的资源中已嵌入的数组型文档,而非跟随链接后去目标资源里提取嵌入内容。
你的代码从http://localhost:8080/api出发调用follow("cars[$all]")时,Traverson会在/api的响应中查找_embedded.cars数组,但你的/api资源里并没有这个嵌入内容——cars数组实际存在于/api/cars资源的_embedded字段中,因此返回空数组。
解决方案
有三种可行的解决方式:
方式一:先跟随到cars资源,再提取嵌入数组
先通过follow("cars")跳转到/api/cars资源,再从返回的文档中取出_embedded.cars数组:
traverson .from("http://localhost:8080/api") .follow("cars") .getResource(function(error, document) { if (!error) { console.log(document._embedded.cars); } });
方式二:直接请求cars资源
跳过根资源,直接从/api/cars发起请求,再提取嵌入数组:
traverson .from("http://localhost:8080/api/cars") .getResource(function(error, document) { if (!error) { console.log(document._embedded.cars); } });
方式三:修改根资源的响应(若业务允许)
如果可以修改/api的HAL响应,在其_embedded中加入cars数组,这样原代码的follow("cars[$all]")就能正常返回数组。修改后的/api响应示例:
{ "_embedded": { "cars": [ { "id": 1, "name": "hotrod", "_links": { "self": { "href": "http://localhost:8080/api/cars/1" } } }, { "id": 2, "name": "junker", "_links": { "self": { "href": "http://localhost:8080/api/cars/2" } } } ] }, "_links": { "self": { "href": "http://localhost:8080/api" }, "cars": { "href": "http://localhost:8080/api/cars" } } }
内容的提问来源于stack exchange,提问作者James
相关产品推荐
相关产品推荐

