如何访问' rel'来自标题中的链接?超媒体链接关系

时间:2017-11-23 06:39:41

标签: javascript json hyperlink hypermedia json-server

我正在使用json服务器和axios

标题

的结果
link: "<http://localhost:3001/posts?_page=1>; rel="first", <http://localhost:3001/posts?_page=2>; rel="next", <http://localhost:3001/posts?_page=5>; rel="last""

如何从链接中使用/访问这些数据?似乎没有关于如何从github解析或访问它的信息。我从github尝试link.rels[:last],但它不起作用。

2 个答案:

答案 0 :(得分:4)

由于JS非常灵活,您只需使用

即可
data = 'link: "<http://localhost:3001/posts?_page=1>; rel="first", <http://localhost:3001/posts?_page=2>; rel="next", <http://localhost:3001/posts?_page=5>; rel="last""'

function parseData(data) {
    let arrData = data.split("link:")
    data = arrData.length == 2? arrData[1]: data;
    let parsed_data = {}

    arrData = data.split(",")

    for (d of arrData){
        linkInfo = /<([^>]+)>;\s+rel="([^"]+)"/ig.exec(d)

        parsed_data[linkInfo[2]]=linkInfo[1]
    }

    return parsed_data;
}

console.log(parseData(data))

输出

{ first: 'http://localhost:3001/posts?_page=1',
  next: 'http://localhost:3001/posts?_page=2',
  last: 'http://localhost:3001/posts?_page=5' }

答案 1 :(得分:0)

var data = 'link: "<http://localhost:3001/posts?_page=1>; rel="first", <http://localhost:3001/posts?_page=2>; rel="next", <http://localhost:3001/posts?_page=5>; rel="last""'

var linkRegex = /\<([^>]+)/g;
var relRegex = /rel="([^"]+)/g;
var linkArray = [];
var relArray = [];
var finalResult = {};
var temp;
while ((temp = linkRegex.exec(data)) != null) {
    linkArray.push(temp[1]);
}
while ((temp = relRegex.exec(data)) != null) {
    relArray.push(temp[1]);
}

finalResult = relArray.reduce((object, value, index) => {
    object[value] = linkArray[index];
    return object;
}, {});

console.log(finalResult);