How to do Axios request from Firebase Cloud Function

后端 未结 2 1748
没有蜡笔的小新
没有蜡笔的小新 2021-02-08 06:30

I\'ve tried the following in Firebase Cloud Function to do an Axios request but it didn\'t work.

    const functions = require(\'firebase-functions\');
    const         


        
2条回答
  •  不知归路
    2021-02-08 07:19

    I changed data.ip to response.data.ip and added return before the two res.status(... lines and the deployed cloud function works for me using Axios when I try it.

    The code I have is

    const functions = require('firebase-functions');
    const axios = require('axios');
    const cors = require('cors')({ origin: true });
    
    exports.checkIP = functions.https.onRequest((req, res) => {
      cors(req, res, () => {
        if (req.method !== "GET") {
          return res.status(401).json({
            message: "Not allowed"
          });
        }
    
        return axios.get('https://api.ipify.org?format=json')
          .then(response => {
            console.log(response.data);
            return res.status(200).json({
              message: response.data.ip
            })
          })
          .catch(err => {
            return res.status(500).json({
              error: err
            })
          })
    
      })
    });
    

    When I invoke the function I get back a reply like { "message": "127.168.121.130" }

提交回复
热议问题