在节点中循环axios request.data出错



我一直试图循环通过axios请求,但我的日志中不断出现错误,我试图循环通过我的数据,返回的数据结构看起来像这个

{2 items
"data":[1 item
0:{...}34 items
]
"pagination":{4 items
"page":0
"itemsPerPage":0
"hasNextPage":true
"hasPrevPage":true
}
}

这是错误

scheduledFunction
SyntaxError: Unexpected token o in JSON at position 1 at JSON.parse (<anonymous>)

这是我的代码

var options = {
method: 'GET',
url: 'https://elenasport-io1.p.rapidapi.com/v2/fixtures',
params: {to: d3, page: '1', from: d2},
headers: {
'x-rapidapi-key': '63836fd5cemshe5de364e7512350p145aebjsn744427db1224',
'x-rapidapi-host': 'elenasport-io1.p.rapidapi.com'
}
};
axios.request(options).then(function (response) {

//console.log(response.data);

data = JSON.parse(response.data); // this is the data you need to process in the request
console.log(data);
data.pagination.forEach(obj => {
Object.entries(obj).forEach(([key, value]) => {
console.log(`${key} ${value}`);
});



}).catch(function (error) {
console.error(error);
});


})

axiosjson格式返回响应。因此,无需解析数据。

更改您的代码

来自data = JSON.parse(response.data);

const data = response.data;

快乐编码:(

只有当数据不是JSON时,才需要将其解析为JSON。在这里,您已经获得了作为JSON的响应数据,不需要再次解析它。

axios.request(options).then(function (response) {
console.log(typeof response); // check the type of response returning already in JSON format
console.log(response); // check the response object and based on key/values process it 
const data = response.data; // if resp contains the data you will get it here.
console.log(data);
data.pagination.forEach(obj => {
Object.entries(obj).forEach(([key, value]) => {
console.log(`${key} ${value}`);
});  
}).catch(function (error) {
console.error(error);
});
})

注意:Axios根据HTTP响应的Content-Type标头解析响应。当响应的内容类型为application/json时,Axios会自动尝试将响应解析为JavaScript对象。有关更多详细信息,请查看此。

此外,分页是一个对象,它不可迭代,而是用于中的/


axios.request(options).then(function (response) {
console.log(typeof response); // check the type of response returning already in JSON format
console.log(response); // check the response object and based on key/values process it 
const data = response.data; // if resp contains the data you will get it here.
console.log(data);
for (let data1 in data.pagination) {
// from the sample response you shared in the question 
console.log(data1) // prints the keys
console.log(data.pagination.data1) // prints the values
}
}).catch(function (error) {
console.error(error);
});
})

最新更新