9

我正在使用 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],但它不起作用。

4

2 回答 2

6

由于 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' }
于 2018-04-16T14:47:23.703 回答
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);

于 2018-04-21T17:28:46.563 回答