2017-04-20 10 views
2

React Nativeアプリで作業しています。私たちは最近、API呼び出しを変更しました。ここでは500で応答でき、問題を詳しく説明してユーザーに提示できるエラーメッセージが表示されます。 APIの応答は次のようになります。クライアント上でReact NativeでHTTPエラーのサーバーレスポンスを表示する方法

{ 
    "error": ["Renter contact info for User 1 missing"] 
} 

、我々は非同期に私たちの要求を行うための標準的なfetch()方法を使用して、応答オブジェクトを引き出すために約束を解決しています。私は500をトリガーする呼び出しの後に応答をログインすると、オブジェクトは次のようになります。

export function request(endpoint:string, parameters:Object, method:string = HTTP.get, timeout:number = 3000):Promise{ 

    return new Promise(async (resolve, reject) => { 
    const payload = { 
     method, 
     headers: { 
     'Accept': CONTENT_TYPE, 
     'Content-Type': CONTENT_TYPE, 
     'Authorization': `Basic ${base64.encode(Config.API_TOKEN)}`, 
     'Auth-Token': await Agents.authToken, 
     }, 
     body: JSON.stringify(parameters), 
    } 

    fetch(apiUrl(endpoint), payload) 
     .then(response => { 
     if(!response.ok) { 
      // ****************** 
      // this is where the 500 error state is caught, but my response object doesn't contain the message sent from the server. 
      reject(response) 
      // ****************** 
     } 

     return response 
     }) 
     .then(resolve) 
     .catch(reject) 
    }) 
} 

どのように確保することができます:

{type: "default", status: 500, ok: false, statusText: undefined, headers: Headers…} 

ここでは、すべてのAPIコールに使用社内request()方法がありますレスポンスオブジェクトにはサーバーからのエラーメッセージが含まれているため、ユーザーに正しく表示できますか?

+0

React Nativeはレスポンスの 'Access-Control-Allow-Origin'ヘッダーの欠如の影響を受けません、そうですか?そうであれば、それはあなたが応答のどんな特性にもアクセスすることができない理由だと思います。 http://stackoverflow.com/a/43361959/441757を参照してください。 – sideshowbarker

答えて

1
fetch(apiUrl(endpoint), payload) 
     .then(response => { 
     if(!response.ok) { 
      response.json().then(function(data) { 
      console.log(data);// your error response 
      },function(error) { 
      //json error 
      }); 
      reject(response) 
      // ****************** 
     } 

     return response 
     }) 

応答はReadableStreamオブジェクトです。あなたは解析するために.json()を使う必要があります

関連する問題