Diorgenes Antunes
Diorgenes Antunes

Reputation: 23

Consuming external api with Firebase Functions

I am trying to consume an external api with Firebase Functions, but it gives a time out error when I use OPTIONS, when I use GET to work normally. I don't want to use const request = require('request'); or var rp = require('request-promise');, as they are obsolete. What may be wrong, I await help from colleagues.

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: '[email protected]',
        name: 'John Dolci',
        phone: 9999999,
        phone_prefix: 66,
        cpf_cnpj: '00000000000',
        cc_emails: '[email protected]',
        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);
    });


}); ```

Upvotes: 1

Views: 2151

Answers (1)

gso_gabriel
gso_gabriel

Reputation: 4670

There are two points that I would point out to your case. First, you need to confirm that you are using the Blaze plan in your billing. As clarified in the official pricing documentation, in case you are not and are trying to use a non Google-owned service, you won't be able to do it and this will cause an error.

The second point would be to use the axios library within your application. It's the one that I believe to be most used with Node.js to allow you access to third-party application within Cloud Functions - I would say that it's pretty easy to use as well. You should find a whole example on using it with third-party API here.

To summarize, take a look at your pricing, as it's the most common issue to be caused and give it a try with axios, to confirm that you can avoid the error with it.

Upvotes: 1

Related Questions