Traverson 库使用 RESTful 网络服务时会抛出 JSONPath 错误

Traverson Library to consume a RESTful webservice throws error with JSONPath

我目前正在尝试让 traverson library 从 SpringBoot 提供的 REST 接口中获取一些信息。

我现在的目标是让 traverson 沿着通往
的道路前行 http ://localhost/users 并使用此代码

获取信息
traverson.from('http://localhost:8090')
    .json()
    .follow('$._links.user')
    .getResource(function(err, resource){
        if(err){
            console.log(err);
            return;    
        }
        console.log(resource);        
    });

调用端点时返回的 json 结构如下所示:

{
  "_links" : {
    "ressource" : {
      "href" : "http://localhost:8090/ressource{?page,size,sort}",
      "templated" : true
    },
    "user" : {
      "href" : "http://localhost:8090/user{?page,size,sort}",
      "templated" : true
    },
    "alert" : {
      "href" : "http://localhost:8090/alert{?page,size,sort}",
      "templated" : true
    }
}

不幸的是,这会导致错误:

Uncaught TypeError: a.step.url.search is not a function

但是,如果我只是在不使用 JSONPath 语法的情况下获取端点,它会为我提供上述结构。 当我弄乱 JSONPath 表达式时,它会产生一个更明智的错误:

[Error: JSONPath expression $.links.user returned no match in document:
{"_links":{"ressource":{"href":"http://localhost:8090/ressource{?page,size,sort}
","templated":true},"user":{"href":"http://localhost:8090/user{?page,size,sort}"
,"templated":true},"alert":{"href":"http://localhost:8090/alert{?page,size,sort}
","templated":true}}]

可能是我遗漏了一些非常明显的东西,这很好...

至少感谢你读到这里:)

可能与谁有关, 经过一些试验和错误后,您必须非常小心您提供的 JSON 路径表达式。

traverson.from('http://localhost:8090')
        .json()
        .follow('$._links.user.href')
        .getResource(function(err, resource){
            if(err){
                console.log(err);
                return;    
            }
            console.log(resource);        
        });

这将在以下时间起作用:

traverson.from('http://localhost:8090')
        .json()
        .follow('$._links.user')
        .getResource(function(err, resource){
            if(err){
                console.log(err);
                return;    
            }
            console.log(resource);        
        });

不会。 原因似乎是 $._links.user 指向一个对象而不是对象属性(参见上面的端点结构)。这会导致 traverson 库中的评估函数导致有点难以理解的错误。

希望有人可以利用这些信息,而不是花时间思考这个问题。

编辑 1:在与图书馆所有者解决问题后,这个问题现在应该不会再发生了