从API获取JSON响应?

问题描述 投票:2回答:2

我发布到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
});

我怎样才能收到消息?

javascript laravel laravel-5
2个回答
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
投票

尝试像这样catch

.catch(function(error){
    console.log(error);
    if (error.response) {
       console.log(error.response.data.message);
    }
});
© www.soinside.com 2019 - 2024. All rights reserved.