2016-11-03 6 views
3

私はフロントエンドでReactjs reduxを、バックエンドとしてRails APIを開発中です。javascriptから読み込み可能なエラーレスポンスを取得するapiを取得しますか?

は、だから今、私はAPIメソッドを取得して、APIを呼び出すが、問題は、私はこれが私の機能

export function create_user(user,userInfoParams={}) { 

    return function (dispatch) { 
     dispatch(update_user(user)); 

     return fetch(deafaultUrl + '/v1/users/', 
      { 
       headers: { 
        'Accept': 'application/json', 
        'Content-Type': 'application/json' 
       }, 
       method: "POST", 
       body: JSON.stringify(userInfoParams) 
      }) 
      .then(function(response) { 
       console.log(response); 
       console.log(response.body); 
       console.log(response.message); 
       console.log(response.errors); 
       console.log(response.json()); 
       dispatch(update_errors(response)); 

       if (response.status >= 400) { 
        throw new Error("Bad response from server"); 
       } 

      }) 
      .then(function(json){ 
       console.log("succeed json re"); 
       // We can dispatch many times! 
       // Here, we update the app state with the results of the API call. 

       dispatch(update_user(json)); 

      }); 


    } 
} 

あるネットワークタブ

の内側に得たもののように読めるエラーメッセージを取得することはできませんですが、エラーが来たとき、私は私のブラウザのネットワークタブをチェックしたときに読める応答メッセージを得る方法を理解できません

これは私がエラーを受け取ったときにネットワークのタブから得たものです。

enter image description here

マイコンソール

enter image description here

これは私のレールのコード

def create 
    user = User.new(user_params) 
    if user.save 
     #UserMailer.account_activation(user).deliver_now 
     render json: user, status: 201 
    else 
     render json: { errors: user.errors }, status: 422 
    end 
    end 

ですが、私は私の関数の内部

感謝することを得ることができる方法を見つけることができません!

+0

console.logの出力を投稿できますか? – Aus

答えて

0

戻ってくる変数がresponse.bodyまたはresponse.messageではありません。

レスポンスオブジェクトのerrors属性を確認する必要があります。

if(response.errors) { 
    console.error(response.errors) 
} 

ここにあなたが実際にサーバーからのエラー応答コードを返すと、あなたの応答にJSONメソッドを呼び出す必要がフェッチAPI

+0

response.errorsの中には何もありません – user3403614

0

まずの.catch()機能を使用する必要がありますhttps://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

チェック。

例:

fetch(`${API_URL}`, { 
     method: 'post', 
     headers: { 
      'Accept': 'application/json', 
      'Content-Type': 'application/json' 
     }, 
     body: JSON.stringify(userInfoParams) 
    }) 
    .then((response) => response.json()) 
    .then((response) => console.log(response)) 
    .catch((err) => { 
     console.log("error", err) 
    }); 

は、それはあなたのために動作しなかった場合、私はコンソールログを知ってみましょう。

+0

ありがとうございましたが、最終的に私はこの中で方法を見つけました。http://stackoverflow.com/questions/40418981/how-can-i-get-errors-value-inside-promise-object-which -return-from-fetch-api/40419846#40419846 – user3403614

1

大丈夫、私はこれを最終的にクラックしたと思います。

テキストは応答オブジェクト内の約束の中に隠されているので、それを見るために約束のように扱う必要があります。

あなたの答えと同様に
fetch(bla) 
    .then(res => { 
     if(!res.ok) { 
     res.text().then(text => throw Error(text)) 
     } 
     else { 
     return res.json(); 
    }  
    }) 
    .catch(err => { 
     console.log('caught it!',err); 
    } 
0

が、応答がOKであれば、もう少し説明して...私は最初にチェックした後、我々は正常な応答を持っている場合のみresponse.text()からエラーを発生させます。したがって、ネットワークエラー(okではない)は、テキストに変換されずに独自のエラーを生成します。その後、これらのエラーは下流のcatchに取り込まれます。ここで

私の解決策である - 私はコアがラッパー関数に関数をフェッチ引っ張っ:私はそれを使用する場合、その時点で必要に応じて

const fetchJSON = (...args) => { 
    return fetch(...args) 
    .then(res => { 
     if(res.ok) { 
     return res.json() 
     } 
     return res.text().then(text => {throw new Error(text)}) 
    }) 
} 

はその後、私は私のレスポンスやエラーを処理する方法を定義します。

fetchJSON(url, options) 
    .then((json) => { 
    // do things with the response, like setting state: 
    this.setState({ something: json }) 
    }) 
    .catch(error => { 
    // do things with the error, like logging them: 
    console.error(error) 
    }) 
関連する問題