gpt4 book ai didi

javascript - 从 API 获取 JSON 响应?

转载 作者:行者123 更新时间:2023-11-29 17:47:31 26 4
gpt4 key购买 nike

我正在发布到一个故意输出失败响应的 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
});

如何获取消息?

最佳答案

我找到一段代码可以帮助你很好地理解catch block 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);
});

关于javascript - 从 API 获取 JSON 响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47870348/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com