如何使用 Google Cloud 功能获取 URL?要求? [英] How to fetch a URL with Google Cloud functions? request?

查看:24
本文介绍了如何使用 Google Cloud 功能获取 URL?要求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将 Google Apps 脚本用于

I used Google Apps Script with

var response = UrlFetchApp.fetch(url, params);

从 api 获得响应.遗憾的是,我需要使用 Drive 中的 Google Apps 脚本处理太多的请求和太多的数据

to get a response from an api. Sadly its too many request and too many data i need to be handled with Google Apps Script in Drive

我现在的想法是切换到谷歌云功能和请求,但它不起作用.

My idea was now to switch to Google cloud functions and request but its not working.

const request = require('request');

const headers = {
    "Authorization" : "Basic " + Buffer.from('blabla').toString('base64')
};

const params = {
    "method":"GET",
    "headers":headers
};

exports.getCheckfrontBookings = (req, res) => {
  let url = 'https://fpronline.checkfront.com/api/3.0/item'

  request({url:url, qs:params}, function(err, response, body) {
    if(err) { console.log(err); return; }
    console.log("Get response: " + response.statusCode);
  });

推荐答案

request 原生支持回调接口,但不返回 Promise,这是您必须在 Cloud Function 中执行的操作.

request supports callback interfaces natively but does not return a promise, which is what you must do within a Cloud Function.

您可以使用 request-promise (https://github.com/request/request-promise) 和 rp(...) 方法返回符合常规 Promises/A+ 的承诺",然后执行以下操作:

You could use request-promise (https://github.com/request/request-promise) and the rp(...) method which "returns a regular Promises/A+ compliant promise" and then do something like:

const rp = require('request-promise');

exports.getCheckfrontBookings = (req, res) => {

  var options = {
    uri: 'https://fpronline.checkfront.com/api/3.0/item',
    headers: {
      Authorization: 'Basic ' + Buffer.from('blabla').toString('base64')
    },
    json: true // Automatically parses the JSON string in the response
  };

  rp(options)
    .then(response => {
      console.log('Get response: ' + response.statusCode);
      res.send('Success');
    })
    .catch(err => {
      // API call failed...
      res.status(500).send('Error': err);
    });
};

这篇关于如何使用 Google Cloud 功能获取 URL?要求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆