Google Cloud Platform Node.js Library - node.js

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-

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.

Related

Nodejs request to a web service with .p12 certificate

So, the title is pretty straightforward. I want to consume a web service from a company and I got .cer and .p12 files. Supposedly, I should use .p12 when making a request. I've imported .cer into windows and I can make requests with postman easily. But when I'm trying to do a request with node.js, I get errors. Here's the code, I'm using request module:
var headersOpt = {
"content-type": "application/json",
};
var options = {
url: 'https://some-url/api',
cert: fs.readFileSync(__dirname + '/certs/myCert.p12'),
headers: headersOpt
};
request.get(options, (error, response, body) => {
console.log(error);
console.log(response);
console.log(body);
});
I get this error:
{ Error: error:0906D06C:PEM routines:PEM_read_bio:no start line
at Object.createSecureContext (_tls_common.js:89:17)
at Object.exports.connect (_tls_wrap.js:1048:48)
at Agent.createConnection (https.js:111:22)
at Agent.createSocket (_http_agent.js:224:26)
at Agent.addRequest (_http_agent.js:192:10)
at new ClientRequest (_http_client.js:256:16)
at Object.request (http.js:39:10)
at Object.request (https.js:239:15)
at Request.start (D:\parser\node_modules\request\request.js:748:32)
at Request.end (D:\parser\node_modules\request\request.js:1512:10)
opensslErrorStack:
[ 'error:140DC009:SSL routines:SSL_CTX_use_certificate_chain_file:PEM lib' ] }
Use pfx property in agentOptions for pkcs12 format :
'use strict';
const request = require('request');
const fs = require('fs');
var options = {
url: 'https://some-url/api',
headers: {
"content-type": "application/json",
},
agentOptions: {
pfx: fs.readFileSync(__dirname + '/certs/myCert.p12'),
passphrase: ''
}
};
request.get(options, (error, response, body) => {
console.log(error);
console.log(response);
console.log(body);
});
If your certificate is self signed, check this

Integration of `connect` on Node.Js failed

Integration of connect on Node.Js failed, problem with node js. This script cant connect it to api . Showing this on browser
Cannot GET /
here is the tutorial click here
var express = require('express')
var jwt = require('jsonwebtoken');
var app = express();
app.get('/PageAfterClickOnSubmitWithZainCash', function (req, res) {
jwt.sign({
amount: 1000,//Product Ammout
serviceType: 'AAA books website',
msisdn: 9647911111111,
orderId: 12345,//optional
redirectUrl: "http://www.yourwebiste.com/zain_order.php",//optional
}, 'secretsecretsecretsecretsecretsecretsecretsecretsecretsecretsecretsecretsecret', {
expiresIn: '4h'
}, function (err, token) {
request.post({
url: 'https://api.zaincash.iq/transaction/init',
form: {
token: token,
merchantId: "572487bca0a4d6f2688c1ee3",
lang: "ar"//optional
}
}, function (err, httpResponse, body) {
var body = JSON.parse(body); // response of body { id : "asdae123asd123asd" }
if (body.id)
return res.redirect('https://api.zaincash.iq/transaction/pay?id=' + body.id);
return res.redirect('/payment?msg=cannot_generate_token');
})
});
});
var connect = require('connect');
var serveStatic = require('serve-static');
var app = connect();
app.listen(5000);
console.log('working on port 5000');
Update
this is how to make server in using Connect
var connect = require('connect');
var http = require('http');
var app = connect();
app.use('/test', function fooMiddleware(req, res) {
res.end('test work')
});
//test work for me check your api request
http.createServer(app).listen(3000);
https://github.com/senchalabs/connect
I run your code on local even its not getting test page with app.get('/test'..).
i am fimilare with express and famous one therefor will suggest Express.js
You are mixing express and connect these are two different framework for node.js
Connect: High performance middleware framework. It was authored by TJ
Holowaychuk on Dec, 2010.
Express: Fast, unopinionated, minimalist
web framework. It was authored by TJ Holowaychuk on Dec, 2010.
express vs connect
here is my code..actualy your server not getting request.its work for test request hope work for your API request too
var express
= require('express')
var jwt = require('jsonwebtoken');
var app = express();
app.get('/test',function(req,res){
res.send('test work properly check your blah API')
})
app.use('/PageAfterClickOnSubmitWithZainCash', function (req, res) {
jwt.sign({
amount: 1000,//Product Ammout
serviceType: 'AAA books website',
msisdn: 9647911111111,
orderId: 12345,//optional
redirectUrl: "http://www.yourwebiste.com/zain_order.php",//optional
}, 'secretsecretsecretsecretsecretsecretsecretsecretsecretsecretsecretsecretsecret', {
expiresIn: '4h'
}, function (err, token) {
request.post({
url: 'https://api.zaincash.iq/transaction/init',
form: {
token: token,
merchantId: "572487bca0a4d6f2688c1ee3",
lang: "ar"//optional
}
}, function (err, httpResponse, body) {
var body = JSON.parse(body); // response of body { id : "asdae123asd123asd" }
if (body.id)
return res.redirect('https://api.zaincash.iq/transaction/pay?id=' + body.id);
return res.redirect('/payment?msg=cannot_generate_token');
})
});
});
app.listen(5000);
console.log('working on port 5000');

Sending/handling GET requests in typescript using Express, Request and Node.js

I'm using a combination of Express and Request (installed using npm) to try to send a get request to get some json from the server. However no matter what I do the body that is returned is "undefined".
This is the code in my server.js file. The json isn't actually what I'm sending, it's just an example as I can't post what I'm actually sending.
import express = require("express");
import bodyParser = require("body-parser");
let app = express();
app.use(bodyParser.json());
app.get('/config', function(req, res){
res.json('{name: test}');
})
app.listen(3000);
I've tried both of the following but both of them say that body is undefined.
import request = require("request");
let req = {
url: `http://localhost:3000/config`,
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
}
request(req, function(error, response, body){
this.config = JSON.parse(body);
})
request(`/config`, function(err, res, body) {
this.config = JSON.parse(body);
});
Does anyone know what I'm doing wrong? I've never used express or request before so any tips would be greatly appreciated.
UPDATE
If I change the request code to the following, the inside of the function is never run. Does anyone know why this would be?
let req = {
url: `http://localhost:3000/config`,
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
}
request(req, function(error, response, body){
console.log("response => "+JSON.parse(body));
return JSON.parse(body);
})
I dont't know if you have posted whole of your server's code, it seems like you missed app.listen(port) so that your server cannot be started up correctly.
Also, if you added if (error) { console.log(error); } at the first line of the callback function of request, you'll find it print an error: [Error: Invalid URI "/config"]
And that's why the body is always undefined: You have to give the full url such like http://localhost:xxxx to request.
In short:
Your server didn't listen to a specific port. app.listen(5678)
Your client didn't know the complete url. request('http://localhost:5678/config', (...)=>{...})
Since OP hasn't got it working and I believe the code he got up there is correct. I may as well post my working solution here to help him get started.
Hopefully this will save you hours of debugging...
Client:
"use strict";
let request = require("request");
let req = {
url: `localhost:4444/config`,
proxy: 'http://localhost:4444',
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
};
request(req, function (err, res, body) {
this.config = JSON.parse(body);
console.log("response => " + this.config);
});
Server:
"use strict";
var express = require("express");
var bodyParser = require("body-parser");
var app = express();
var config = require('config');
app.use(bodyParser.json());
app.get('/config', function(req, res){
res.json('{name: test}');
});
// Start the server
app.set('port', 4444);
app.listen(app.get('port'), "0.0.0.0", function() {
console.log('started');
});
Output:
response => {name: test}

I'm using .pfx certification in my node.js https server and I can't use 'passphrase' in option

I'm currently making an web application with node.js and https.
So I try to use my .pfx(I got the file from here http://www.cert-depot.com/) for certification required for https, like following code:
var https = require('https');
var fs = require('fs');
var options = {
pfx: fs.readFileSync('./8ab20f7b-51b9-4c09-a2e0-1918bb9fb37f.pfx')
passphrase: 'password'
};
var server = https.createServer(options, function (request, response) {
fs.readFile('index.html', function (error, data) {
response.writeHead(200, {'Content-Type': 'text/html'});
response.end(data);
});
}).listen(12345, function(){
console.log('server running');
});
But when I start this code with node.js, I'm getting an error message in my windows console:
passphrase: 'password'
Unexpected identifier
My code is very similar to the official guide page of Node.js (http://nodejs.org/api/https.html#https_https_createserver_options_requestlistener), but I can't start my https server.
What's wrong with my passphrase?
(I'm running node.js in Windows 8 64bit.)
I guess the missing comma between your pfx and passphrase properties is what cause the error. Here I added the comma:
var options = {
pfx: fs.readFileSync('./8ab20f7b-51b9-4c09-a2e0-1918bb9fb37f.pfx'),
passphrase: 'password'
};
I stick a promise wrapper on my implementation of it and keep it async (ES2015).
lib/pfx.js
import { readFile } from 'fs'
import { resolve as resolvePath } from 'path'
export const CERTIFICATE_ROOT = resolvePath(__dirname, '..', 'etc', 'certificates')
export const getCertificatePath = filename => resolvePath(CERTIFICATE_ROOT, filename)
export function readCertificate(filename) {
let certificatePath = getCertificatePath(filename)
return new Promise((resolve, reject) => {
readFile(certificatePath, (err, certificate) => {
if (err)
return reject(err)
resolve(certificate)
})
})
}
export function readPfx(filename, passphrase) {
assert.typeOf(passphrase, 'string', 'passphrase must be a string')
assert.isAbove(passphrase.length, 0, 'passphrase must not be empty')
return readCertificate(filename).then(pfx => ({ pfx, passphrase }))
}
and usage
lib/app.js
import { readPfx } from './pfx'
readPfx('8ab20f7b-51b9-4c09-a2e0-1918bb9fb37f.pfx', process.env.PASSPHRASE)
.then(opts => /* start server here */)
.catch(err => /* handle errors */)

How to make a external API call inside express server?

Hello I ve been trying to implement OneSignal API on my dashboard and I wonder if it is possible to make a API external call inside express server.
Here is an example:
var sendNotification = function(data) {
var headers = {
"Content-Type": "application/json; charset=utf-8",
"Authorization": "Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj"
};
var options = {
host: "onesignal.com",
port: 443,
path: "/api/v1/notifications",
method: "POST",
headers: headers
};
var https = require('https');
var req = https.request(options, function(res) {
res.on('data', function(data) {
console.log("Response:");
console.log(JSON.parse(data));
});
});
req.on('error', function(e) {
console.log("ERROR:");
console.log(e);
});
req.write(JSON.stringify(data));
req.end();
};
Here it is the app route
app.post('/path', function(req, res){
var message = {
app_id: "5eb5a37e-b458-11e3-ac11-000c2940e62c",
contents: {"en": "English Message"},
included_segments: ["All"]
};
sendNotification(message);
});
Thank you!
I wonder if it is possible to make a API external call inside express
server.
Sure, you can contact any external server from a node.js app with http.request() like you are showing or one of the higher level modules built on top of that like the request module.
Here's a simple example from the request module home page:
const request = require('request');
request('http://www.google.com', function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body) // Show the HTML for the Google homepage.
}
});
Or, using promises:
const rp = require('request-promise');
rp('http://www.google.com').then(body => {
console.log(body);
}).catch(err => {
console.log(err);
});

Resources