简体   繁体   English

如何使用Axios捕获服务器代码错误

[英]How do I catch a server code error using Axios

I have made a GET request to an API which rejects GET requests with a 400 error (and "Invalid request") response; 我向一个API发出了GET请求,该API拒绝了带有400错误(和“无效请求”)响应的GET请求; and while I can catch and handle the response data, there is another error line which I can't catch: 虽然我可以捕获和处理响应数据,但是还有另一条我无法捕获的错误行:

GET https:// API address /test 400 获取https:// API地址 / test 400

My code is as follows: 我的代码如下:

try {
    let res = await this.axios.get(API)
    console.log(res.data)
} catch (error) {
    console.log(error.response.data)
}

I did also try this as a promise chain (with a catch) - but same result and I was thinking that wrapping everything in a try catch would do the trick. 我也尝试过将其作为一个承诺链(带有捕获)-但结果相同,而且我认为将所有内容都包裹在try catch中可以解决问题。

My API code (hosted on Firebase) is as follows: 我的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!");
    })
});

First line is when I send a POST request, and the rest comes back after the GET request: 第一行是当我发送POST请求时,其余的在GET请求之后返回: 安慰

How do I handle that GET error? 我该如何处理该GET错误? And where is it coming from? 它是从哪里来的?

If I correctly understand your question, it seems you are calling the Cloud Function with a wrong URL. 如果我正确理解您的问题,则似乎您是在使用错误的URL调用Cloud Function。

You use 你用

 https://us-central1-xxxxxx.cloudfunctions.net/helloWorld

as shown in the first version of your question, 如问题的第一个版本中所示,

when you should use 什么时候应该使用

 https://us-central1-xxxxxx.cloudfunctions.net/test

since your Cloud Function is defined with 因为您的Cloud Function是使用

exports.test = functions.https.onRequest()

You'll find the corresponding doc here: https://firebase.google.com/docs/functions/http-events#invoke_an_http_function 您可以在这里找到相应的文档: https : //firebase.google.com/docs/functions/http-events#invoke_an_http_function


Update following your comment: 根据您的评论进行更新:

It is normal that GET shows an error since you have the following code: GET显示错误是正常的,因为您具有以下代码:

 if (request.method !== 'POST') {
   return response.status(400).send('Invalid request.')
 }

Since GET is not a POST you enter this if and get a 400 error... 由于GET不是POST,因此您输入if并得到400错误...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM