【问题标题】:Use firebase cloud function to send GET request to non-google server使用 firebase 云功能向非谷歌服务器发送 GET 请求
【发布时间】:2019-12-25 02:42:42
【问题描述】:

我正在设置 Firebase 云函数以对非 Google 服务进行 API 调用。对于测试,我使用 jsonplaceholder 作为 API。我收到的响应是 403 错误。

我已经查看了similar 的其他问题,但答案表明升级到付费 Firebase 帐户可以解决问题。升级到 blaze plan 后,我修复了 Firebase 阻止传出 http 调用的问题,但我现在遇到了我尝试从中发出请求的任何 API 返回的 403 错误。


import * as functions from 'firebase-functions';
const cors = require('cors')({origin: true});

export const getJson = functions.https.onRequest(async (req, res) => {
    cors( req, res, async ()=> {
        try {
            let info = await req.get('https://jsonplaceholder.typicode.com/todos/1');
            res.send(info);
        } catch (error) {
            res.status(500).send(`catch block hit: ${error}`);
        }
    })
})

我希望 API 调用返回一个 json 对象:

{
  "userId": 1,
  "id": 1,
  "title": "delectus aut autem",
  "completed": false
}

我收到的回复是:

 "Failed to load resource: the server responded with a status of 403 ()"

注意:如果我从postman 生成get request,我可以收到预期的结果

感谢您的帮助,谢谢。

【问题讨论】:

标签: angular firebase google-cloud-functions


【解决方案1】:

req 是发送到服务器的请求,req.get() 用于获取该请求的标头。如果你想提出一个请求,你需要自己触发。您可以使用原始节点(例如https 包)或引入axiosisomorphic-fetch 之类的包来执行此操作。像这样的:

const functions = require('firebase-functions')
const axios = require('axios')
const cors = require('cors')({ origin: true });

export const getJson = functions.https.onRequest(async (req, res) => {
  cors( req, res, async ()=> {
    try {
      let info = await axios.get('https://jsonplaceholder.typicode.com/todos/1');
      res.send(info.data);
    } catch (error) {
      res.status(500).send(`catch block hit: ${error}`);
    }
  })
})

【讨论】:

    猜你喜欢
    • 2017-09-10
    • 2019-01-23
    • 1970-01-01
    • 1970-01-01
    • 2020-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-28
    相关资源
    最近更新 更多