我试图在Node.js中获取并解析下面返回的JSON。看来问题在于节点代码正在尝试解析包含换行符的JSON字符串,但是我不确定如何避免这种情况,以及为什么提取在chrome devtools中起作用。我猜问题出在我对https请求的简单了解,所以如果有人可以解释出什么问题了,我将不胜感激。
const url = "https://beta.charitycommission.gov.uk/umbraco/api/charityApi/getSearchResults?searchText=&pageNumber=1&contextId=1126&onlyShow=&&&&&&&"
我可以在域上打开的chrome devtools中成功运行此命令。另外,JSON似乎会自动解析为一个我没有想到的对象。
fetch(url).then(res => res.json()).then(json => console.log(json.pageItems))
我已经在节点中尝试了以下方法,但是没有用。
const fetch = require("node-fetch");
await fetch(url).then(res => res.json()); // Unexpected token in JSON at position 0
const rp = require('request-promise-native');
const json = await rp({uri: url}) // returns JSON string with newline characters
JSON.parse(json) // Unexpected token in JSON at position 0