dog*_*tar 4 json fetch react-native
抱歉这个愚蠢的问题。我对原生反应比较陌生。我有 fetch 工作,所以我可以从服务器获取 json 响应。如果出现错误,服务器 API 将返回一个字符串,如果成功则返回一个 json 对象。有什么方法可以比较响应以查看它是字符串还是json变量?
不知道如何实现上述任何帮助将不胜感激。
这是我的代码
API.js
var API = {
SetupBuyOnline(email, serialNumber, platformType) {
var url = 'https://<urlomitted>/SetupBuyOnline';
return fetch(url, {
method: 'GET',
headers: {
'Content-Type': 'application/json; charset=UTF-8',
'Accept': 'application/json',
'operating_system': platformType,
'email': email,
'serialNumber': serialNumber
}
}).then((res) => res.json());
}
};
Run Code Online (Sandbox Code Playgroud)
找到 userScreen.js
findUserScreen(){
// this.props.navigation.navigate('JoinNowScreen')
StudentApi.SetupBuyOnline('useremail@test.com', deviceId, "iOS")
.then((responseData) => {
if(typeof(responseData) == 'string')
{
console.log('got api call ' + responseData);
alert('test = ' + responseData);
}
else
{
console.log('got api call ' + responseData);
alert(responseData);
}
})
}
Run Code Online (Sandbox Code Playgroud)
不知道我做错了什么。提前致谢
除了改变你==的===(严格平等)不多。但会以正常的平等工作。
不知道你做错了什么,因为这段代码工作得很好。
我会做的是有一个像这样的 JSON 响应:
"{
error: true,
}"
"{
error: false,
data: yourDataSentByTheServer!
}"
Run Code Online (Sandbox Code Playgroud)
这样你只需要检查你的 JSON 响应中是否有错误属性。
"{
error: true,
}"
"{
error: false,
data: yourDataSentByTheServer!
}"
Run Code Online (Sandbox Code Playgroud)
function stringType(){
const responseData = 'hello';
if(typeof(responseData) === 'string')
{
console.log('got api call ' + responseData);
alert('test = ' + responseData);
}
else
{
console.log('got api call ' + responseData);
alert(responseData);
}
}
function objType(){
const responseData = { 1:'hello', 2: 'koko' }
if(typeof(responseData) === 'string')
{
console.log('got api call ' + responseData);
alert('test = ' + responseData);
}
else
{
console.log('got api call ' + responseData);
alert(responseData);
}
}Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11956 次 |
| 最近记录: |