【问题标题】:Get a JSON response from an API?从 API 获取 JSON 响应?
【发布时间】:2018-05-31 21:46:23
【问题描述】:

我正在发布到故意输出失败响应的 api:

return response()->json([
        'message' => 'Record not found',
    ], 422);

在 Chrome 开发工具中,我可以看到我收到了 422 响应,响应为 {"message":"Record not found"}

我希望在 javascript 中获取消息并记录它,但我很难做到这一点,这是我的 javascript:

axios.post('/api/test', {
    name: 'test'
})
.then(function (response) {
    console.log(response);
})
.catch(function (error) {
    console.log(error) //this is Error: Request failed with status code 422
    console.log(error.message); //this is blank
});

我怎样才能得到消息?

【问题讨论】:

    标签: javascript laravel laravel-5


    【解决方案1】:

    我找到了一段代码,可以帮助你很好地理解catch块here

    axios.post('/api/test', {
        name: 'test'
    })
    .then((response) => {
        // Success
    })
    .catch((error) => {
        // Error
        if (error.response) {
            // The request was made and the server responded with a status code
            // that falls out of the range of 2xx
            // console.log(error.response.data);
            // console.log(error.response.status);
            // console.log(error.response.headers);
        } else if (error.request) {
            // The request was made but no response was received
            // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
            // http.ClientRequest in node.js
            console.log(error.request);
        } else {
            // Something happened in setting up the request that triggered an Error
            console.log('Error', error.message);
        }
        console.log(error.config);
    });
    

    【讨论】:

      【解决方案2】:

      尝试像这样catch

      .catch(function(error){
          console.log(error);
          if (error.response) {
             console.log(error.response.data.message);
          }
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-09-16
        • 2019-04-25
        • 2016-08-01
        • 2022-06-28
        • 2020-02-02
        相关资源
        最近更新 更多