我已向 API 发出 GET 请求,该 API 拒绝 GET 请求并返回 400 错误(和“无效请求”)响应;虽然我可以捕获并处理响应数据,但还有另一个我无法捕获的错误行:
GET https://API address/test 400
我的代码如下:
try {
let res = await this.axios.get(API)
console.log(res.data)
} catch (error) {
console.log(error.response.data)
}
我也尝试过将其作为 promise 链(带有 catch) - 但结果相同,我认为将所有内容包装在 try catch 中就可以解决问题。
我的 API 代码(托管在 Firebase 上)如下:
exports.test = functions.https.onRequest((request, response) => {
cors(request, response, () => {
if (request.method !== 'POST') {
return response.status(400).send('Invalid request.')
}
response.status(200).send("Hello from Firebase!");
})
});
第一行是当我发送 POST 请求时,其余的在 GET 请求后返回:
如何处理 GET 错误?它从哪里来?
最佳答案
如果我正确理解你的问题,那么你似乎使用了错误的URL调用云函数。
您使用
https://us-central1-xxxxxx.cloudfunctions.net/helloWorld
如您问题的第一个版本所示,
什么时候应该使用
https://us-central1-xxxxxx.cloudfunctions.net/test
因为您的云功能是用
定义的exports.test = functions.https.onRequest()
您可以在这里找到相应的文档:https://firebase.google.com/docs/functions/http-events#invoke_an_http_function
<小时/>更新您的评论:
GET 显示错误是正常的,因为您有以下代码:
if (request.method !== 'POST') {
return response.status(400).send('Invalid request.')
}
由于 GET 不是 POST,因此您输入此 if 并收到 400 错误...
关于javascript - 如何使用 Axios 捕获服务器代码错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54492239/