0
我正在使用laravel(php)后端进行react-native项目。我有一个类AuthService与方法登录(用户名,密码),它返回一个promoise,解决用户和拒绝错误。这些错误将在JSON中进行响应,以便我可以向用户显示特定的错误,但是由于可能会发生意外错误,我还希望为使用组件提供一个json对象。Promise拒绝为json
return fetch(Config.AUTH_URL, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: email, //provided
password: password //provided
})
})
.then(response=> {
if (response.ok) {
return response.json().then(user=> {
console.log(user);
AsyncStorage.setItem('auth.token', user.api_token);
AsyncStorage.setItem('user_name', user.user.name);
AsyncStorage.setItem('user_email', user.user.email);
})
} else {
if (response.status == 422) {
//this needs to be rejected, but gives error
return Response.reject(response.json());
} else {
//when the response from server is unexpected error (eg. 500 without json data),I still want to reject with a json object
return Promise(null,()=> {
return {"email": ["Technical problem, try later"]}
});
}
}
}, err=> {
throw Error({"email": ["Technische fout. Probeer het opnieuw"]});
});
感谢您的答复,但提取API没有按不提供解析回调,它只提供响应对象。我怎样才能继续使用拒绝和解决? @Burak Karasoy –
@DesterDezzods答案更新。你可以使用另一个组件,比如'require'它提供了解析和拒绝。 –
或者使用'fetch'并抛出错误。 – NiFi