gpt4 book ai didi

reactjs - 如何修复 react-native 中的 GET JSON 响应问题

转载 作者:行者123 更新时间:2023-12-05 08:07:16 25 4
gpt4 key购买 nike

我正在使用来 self 的 React Native 应用程序的 API。但是请求响应总是返回一个字符串,即使我尝试解析我也看到错误。

我使用了 axios、superagent 和 fetch api。但我仍然面临一个错误,同样的错误。

fetch(`http://fonte83.com.br/wp-json/wp/v2/posts?page=1&_embed`, {
method: "GET",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
}
}).then(result => result.json()).then(text => console.log(text))

此代码在导航器控制台或其他应用程序上运行良好,但在我的应用程序上却一团糟。我尝试使用此代码在 axios 中转换另一个代码,但仍然遇到错误。

if (typeof data === 'string') {
try {
if (!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
};
}
data = JSON.parse(data.trim(''));
} catch (e) {
throw {message: 'can not JSON.parse the response'}
}
}

我收到此错误:“位置 0 处的 JSON 中的意外标记”。

上面这两个代码来自不同的尝试

有什么奇怪的,因为代码在其他位置运行。谁能帮帮我?

最佳答案

Fetch API 在 Promise result.json() 上返回一个 JSON 对象,因此您的代码应该是:

fetch(`http://fonte83.com.br/wp-json/wp/v2/posts?page=1&_embed`, {
method: "GET",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
}
}).then(result => result.json())
.then(obj => {
console.log('Title of the first post: ' + obj[0].title.rendered);
console.log('Content of the first post: ' + obj[0].content.rendered);
});

您正在尝试解析一个已被 result.json() 解析的对象

关于reactjs - 如何修复 react-native 中的 GET JSON 响应问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55579245/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com