从 jsonp 获取承诺获取 json
Get json from jsonp fetch promise
我刚开始使用 react-native,我正在做文档中的经典示例作为基础...
fetch('https://facebook.github.io/react-native/movies.json')
.then((response) => response.json())
.then((responseJson) => {
return responseJson.movies;
})
.catch((error) => {
console.error(error);
});
在该示例中,使用适当的 json 一切正常。
但是,在我的特定情况下,唯一可用的 api 响应是 JSONP 而不是 JSON。没有基本的 JSON 可用。所以我收到关于“(”的错误。
所以 JSON 而不是
{"id": "1", "movies" : [ { "id" : "123" } ] }
我收到 JSONP 赞
?( {"id": "1", "movies" : [ { "id" : "123" } ] });
但是,我不确定我可以做些什么来通过 fetch promises 得到 JSON ?我如何使用我自己的函数之一来操纵响应,或者有更自然的方法吗?
所以在第一个 then() 中,我不确定我能做些什么来得到 json(我已经尝试对响应进行操作,但这似乎只是在看承诺,所以我不确定 react-native fetch 是如何操作的。
我建议使用 response.text()
而不是 response.json()
,去除周围的噪音,然后解析 JSON 字符串。
fetch('YOUR URL HERE')
.then((response) => response.text())
.then((responseText) => {
const match = responseText.match(/\?\((.*)\);/);
if (!match) throw new Error('invalid JSONP response');
return JSON.parse(match[1]).movies;
})
.catch((error) => {
console.error(error);
});
我刚开始使用 react-native,我正在做文档中的经典示例作为基础...
fetch('https://facebook.github.io/react-native/movies.json')
.then((response) => response.json())
.then((responseJson) => {
return responseJson.movies;
})
.catch((error) => {
console.error(error);
});
在该示例中,使用适当的 json 一切正常。
但是,在我的特定情况下,唯一可用的 api 响应是 JSONP 而不是 JSON。没有基本的 JSON 可用。所以我收到关于“(”的错误。
所以 JSON 而不是
{"id": "1", "movies" : [ { "id" : "123" } ] }
我收到 JSONP 赞
?( {"id": "1", "movies" : [ { "id" : "123" } ] });
但是,我不确定我可以做些什么来通过 fetch promises 得到 JSON ?我如何使用我自己的函数之一来操纵响应,或者有更自然的方法吗?
所以在第一个 then() 中,我不确定我能做些什么来得到 json(我已经尝试对响应进行操作,但这似乎只是在看承诺,所以我不确定 react-native fetch 是如何操作的。
我建议使用 response.text()
而不是 response.json()
,去除周围的噪音,然后解析 JSON 字符串。
fetch('YOUR URL HERE')
.then((response) => response.text())
.then((responseText) => {
const match = responseText.match(/\?\((.*)\);/);
if (!match) throw new Error('invalid JSONP response');
return JSON.parse(match[1]).movies;
})
.catch((error) => {
console.error(error);
});