【问题标题】:Consuming external api with Firebase Functions使用 Firebase 函数使用外部 api
【发布时间】:2020-12-27 11:38:53
【问题描述】:

我正在尝试使用 Firebase 函数使用外部 api,但是当我使用 OPTIONS 时,当我使用 GET 正常工作时,它会给出超时错误。 我不想使用 const request = require('request');var rp = require('request-promise');,因为它们已经过时了。 可能有什么问题,我等待同事的帮助。

const express = require('express');
const cors = require('cors');

const app = express();
// Permitir solicitações de origem cruzada automaticamente
app.use(cors({
    origin: true
}));
//app.use(cors());


app.get('/criarcliente', (req, res) => {

    let uri = "https://api.iugu.com/v1/customers?api_token=<mytoken>";
    let headers = {
        'Content-Type': 'application/json'
    }

    let body = {
        custom_variables: [{
            name: 'fantasia',
            value: 'Dolci Technology'
        }, {
            name: 'vendedor',
        value: ''
        }],
        email: 'teste1@teste1.com',
        name: 'John Dolci',
        phone: 9999999,
        phone_prefix: 66,
        cpf_cnpj: '00000000000',
        cc_emails: 'test@test.com',
        zip_code: '78520000',
        number: '49',
        street: 'Name Street',
        city: 'Guarantã do Norte',
        state: 'MT',
        district: 'Jardim Araguaia'
    }

    var options = {
        method: 'POST',
        uri: uri,
        body: body,
        headers: headers,
        json: true
    };

    const https = require('https');

    var req = https.request(options, (resp) => {
        let data = '';
        resp.on('data', (chunk) => {
            data += chunk;
        });
        resp.on('end', () => {
            var result = JSON.parse(data);
            res.send(result);
        });
        console.log("aqui");
    }).on("error", (err) => {
        console.log("Error: " + err.message);
    });


}); ```

【问题讨论】:

    标签: javascript node.js firebase google-cloud-functions


    【解决方案1】:

    我要针对您的情况指出两点。首先,您需要确认您在帐单中使用的是 Blaze 计划。正如官方pricing documentation 中所阐明的那样,如果您不是并且正在尝试使用非 Google 拥有的服务,您将无法这样做,这将导致错误。

    第二点是在您的应用程序中使用axios 库。我认为它最常与 Node.js 一起使用,以允许您访问 Cloud Functions 中的第三方应用程序——我想说它也很容易使用。你应该找到一个完整的例子来使用第三方 API here

    总而言之,看看您的定价,因为这是最常见的问题,并通过axios 尝试一下,以确认您可以避免错误。

    【讨论】:

    • 感谢您的回答,它已经对我帮助很大,我使用 Blaze 计划。使用 GET 我通常可以,我只有 PUT 和 POST 的问题,你告诉我你使用 GET 的这个例子,你没有使用 POST 或 PUT 的例子吗?
    • 嗨@LucasDolci,您可以查看herehere,例如使用POST。请,如果您认为我的回答对您有帮助,请考虑接受它,以便社区可以确认此案例已得到妥善解决/帮助。 :)
    猜你喜欢
    • 1970-01-01
    • 2019-05-26
    • 2021-12-04
    • 2019-11-14
    • 1970-01-01
    • 1970-01-01
    • 2023-03-04
    • 1970-01-01
    • 2020-09-06
    相关资源
    最近更新 更多