从API获取JSON响应?

时间:2017-12-18 14:16:54

标签: javascript laravel laravel-5

我发布到api,其中故意输出失败的响应:

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

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

的422响应

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

我如何收到消息?

2 个答案:

答案 0 :(得分:3)

我找到了一个代码,可以帮助您很好地理解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);
});

答案 1 :(得分:1)

尝试catch这样:

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