如何从javascript Fetch api获取Readable错误响应? [英] How to get Readable error response from javascript Fetch api?

查看:97
本文介绍了如何从javascript Fetch api获取Readable错误响应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在前端和React api上开发Reactjs redux.

I am working on Reactjs redux on front-end and Rails api as a back-end.

所以现在我用Fetch api方法调用api,但问题是我无法获得像在网络标签中一样的可读错误消息

So now i call api with Fetch api method but the problem is i cannot get readable error message like what i got inside the network tabs

这是我的职责

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));

            });


    }
}

但是当出现错误时,我无法弄清楚如何获得可读的响应消息,就像我在浏览器网络标签上查看时得到的消息一样

But when errors came i cannot figure out how to get readable response message like i got when i check on my browser network tabs

这就是我在遇到错误时从网络"标签中获得的信息.

So this is what i got from the network tabs when i got errors.

我的控制台

这是我的rails代码

This is my rails code

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

但是我找不到如何在函数中获取它

But i cannot find out how can i get that inside my function

谢谢!

推荐答案

好的,我想我终于破解了.

ok, I think I finally cracked this.

文本隐藏在响应对象内的promise中,因此需要像看待promise一样对其进行处理.

text is hidden inside promise within response object, so it needs to be handled like a promise to see it.

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);
    }

这篇关于如何从javascript Fetch api获取Readable错误响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆