Google Cloud Platform Node.js Library

I am creating a google function. However, when I try to deploy to Google Cloud Platform, I am getting this error

ERROR: (gcloud.beta.functions.deploy) OperationError: code=3, message=Function load error: Code in file index.js can't be loaded. Did you list all required modules in the package.json dependencies? Detailed stack trace: Error: Cannot find module 'request'

How do I upload/install the 'request' library in google cloud platform?

Code Snippet

'use strict';
const https = require('https');
const host = 'https://www.example.com';
const clientId = 'qpopMIGtVdeIdVk3oEtr2LGbn8vTeTWz';
const clientSecret = 'eUnsWQ8y3AuiFHJu';
const grant_type = 'client_credentials';
const resource = 'b.microsoft.com/4fa4b4a7-d34f-49af-8781-c8b39f0cf770';
const request = require("request");


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

  // Call the Apigee API
  callGetOAuthToken().then((output) => {
    // Return the results from the APigee  to DialogFlow
    res.setHeader('Content-Type', 'application/json');
    res.send(JSON.stringify({ 'speech': output, 'displayText': output }));
  }).catch((error) => {     
        // If there is an error let the user know
    res.setHeader('Content-Type', 'application/json');
    res.send(JSON.stringify({ 'speech': error, 'displayText': error }));
  });
};
function callGetOAuthToken () {
  return new Promise((resolve, reject) => {

    let path = '/customers/v1/accesstoken';

    var authHeader =  Buffer.from(clientId + ':' + clientSecret).toString('base64');
    var post_options = {
                          url: host + path,
                          method: 'POST',
                          headers: 
                          {
                            'Content-Type': 'application/x-www-form-urlencoded',
                            'Authorization': 'Basic ' + authHeader,
                            'grant_type':grant_type
                          }
                        };

    // Make the HTTP request to get the weather
    request(post_options, function(err, res, body) {
        let output = JSON.parse(body);
        console.log(output);
        resolve(output);
      });   
  });
}

-Alan-

1 answer

  • answered 2018-04-17 05:59 ansibly

    Read through the Google Cloud documentation regarding dependencies: https://cloud.google.com/functions/docs/writing/dependencies

    List the 'request' module as a dependency in your package.json file if using the gcloud CLI.

    Or, run 'npm install --save request' in the folder containing your cloud function and upload your pre-installed dependencies as part of your ZIP file.