代码之家  ›  专栏  ›  技术社区  ›  xon52

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

  •  0
  • xon52  · 技术社区  · 6 年前

    获取https:// API地址 /测试400

    我的代码如下:

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

    我也尝试过将其作为一个承诺链(带有一个捕获),但是同样的结果,我认为用一个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请求后返回: console

    1 回复  |  直到 6 年前
        1
  •  1
  •   Renaud Tarnec    6 年前

    你用

     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.')
     }