从API获取JSON响应?
我张贴到一个API,其中一个失败的回应是故意的输出:从API获取JSON响应?
return response()->json([ 'message' => 'Record not found',
], 422);
在Chrome浏览器开发工具,我可以看到我得到的
在javascript中我希望响应422响应获取消息并记录下来,但我很努力这么做,这里是我的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
});
我怎样才能得到消息?
回答:
我发现了一个代码,可以帮助您了解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);
});
回答:
尝试catch
这样的:
.catch(function(error){ console.log(error);
if (error.response) {
console.log(error.response.data.message);
}
});
以上是 从API获取JSON响应? 的全部内容, 来源链接: utcz.com/qa/264034.html