I have a nodejs app which is integrating to simplybook.me using jsonrpc. the integration is working good on my local server. but the client is failed to initialize when I run it over gcloud app.
file: index.js: `
const JSONRpcClient = require('../json-rpc');
const apiUrl = 'https://user-api.simplybook.me';
const SIMPLYBOOK_API_KEY = "[[REDACTED]]"
const SIMPLYBOOK_COMPANY_NAME = "dssdemo"
const loginClient = new JSONRpcClient({
url: `${apiUrl}/login`,
onerror: (e:any)=>logger.error(e),
});
console.log("problem", loginClient);
const clientToken = loginClient.getToken(SIMPLYBOOK_COMPANY_NAME, SIMPLYBOOK_API_KEY);
logger.info('SimplyBook instantiated');`
file: json-rpc.js
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const logger_1 = require("../libs/logger");
/* eslint-disable */
const jsdom = require("jsdom");
const dom = new jsdom.JSDOM('');
var jQuery = require("jquery")(dom.window);
/**
* JSON-RPC Client Exception class
*
* @param String code
* @param String message
*/
var JSONRpcClientException = function (code, message) {
this.code = code;
this.message = message;
};
JSONRpcClientException.prototype = jQuery.extend(JSONRpcClientException.prototype, {
/**
* Magic method. COnvert object to string.
*
* @return String
*/
toString: function () {
return '[' + this.code + '] ' + this.message;
}
});
/**
* JSON-RPC Client
*
* @param Object options
*/
var JSONRpcClient = function (options) {
JSONRpcClient.prototype.setOptions(options);
JSONRpcClient.prototype.init();
};
JSONRpcClient.prototype = jQuery.extend(JSONRpcClient.prototype, {
/**
* Default options
*/
options: {
'onerror': function () { },
'onsuccess': function () { },
'url': '',
'headers': {}
},
current: 1,
onerror: null,
onsuccess: null,
onstart: null,
/**
* Init client
*/
init: function () {
this.onerror = this.getParam('onerror');
this.onsuccess = this.getParam('onsuccess');
this.initMethods();
},
/**
* Init API methiods by url
*/
initMethods: function () {
var instance = this;
// get all methods
jQuery.ajax(this.getParam('url'), {
'async': false,
'success': function (data) {
if (data.methods) {
// create method
jQuery.each(data.methods, function (methodName, methodParams) {
var method = function () {
var params = new Array();
for (var i = 0; i < arguments.length; i++) {
params.push(arguments[i]);
}
var id = (instance.current++);
var callback = params[params.length - 1];
var request = { jsonrpc: '2.0', method: methodName, params: params, id: id };
var async = false;
if (jQuery.type(callback) == 'function') {
async = true;
params.pop();
}
var res = null;
// API request
jQuery.ajax(instance.getParam('url'), {
'contentType': 'application/json',
'type': methodParams.transport,
'processData': false,
'dataType': 'json',
'cache': false,
'data': JSON.stringify(request),
'headers': instance.getParam('headers'),
'async': async,
'success': function (result) {
if (jQuery.type(result.error) == 'object') {
// res = JSONRpcClientException(result.error.code, result.error.message);
// instance.onerror(res);
logger_1.logger.info(result.error.message);
}
else {
res = result.result;
if (jQuery.type(callback) == 'function') {
callback(res);
}
}
instance.onsuccess(res, id, methodName);
}
});
if (!async) {
return res;
}
};
instance[methodName] = method;
});
}
else {
throw new Error("Methods could not be found");
}
}
});
},
/**
* Set client options
*
* @param Object options
*/
setOptions: function (options) {
this.options = jQuery.extend({}, this.options, options);
},
/**
* Get client param, if param is not available in this.options return defaultValue
*
* @param String key
* @param mixed defaultValue
* @return mixed
*/
getParam: function (key, defaultValue) {
if (jQuery.type(this.options[key]) != 'undefined') {
return this.options[key];
}
return defaultValue;
}
});
module.exports = JSONRpcClient;
//# sourceMappingURL=json-rpc.js.map
I have deployed my app using gcloud app deploy.
file: app.yaml:
runtime: nodejs12
this is the problematic code. node my app is running and other features are working normally but this is problematic. which is running locally but not on the server and yes port is 8080.
here is the screenshot of error on server but it's working perfectly on my local Please help and point me in the right direction. Thanks
It's difficult to understand exactly what's going wrong but...
I built a simple gRPC-JSON example using the NPM documentation .
I published the server as a Google Cloud Function and the client as an App Engine (standard) app.
The following works for me:
QUESTION="65449123"
PROJECT=dazwilkin-$(date +%y%m%d)-${QUESTION} && echo ${PROJECT}
BILLING=$(gcloud alpha billing accounts list --format="value(name)")
gcloud projects create ${PROJECT}
gcloud beta billing projects link ${PROJECT} \
--billing-account=${BILLING}
for SERVICE in cloudfunctions cloudbuild
do
gcloud services enable ${SERVICE}.googleapis.com \
--project=${PROJECT}
done
gcloud app create \
--region=us-central \
--project=${PROJECT}
gcloud functions deploy server \
--allow-unauthenticated \
--source=./server \
--entry-point=server \
--runtime=nodejs14 \
--trigger-http \
--region=us-central1 \
--project=${PROJECT}
SERVER_URL=$(\
gcloud functions describe server \
--project=${PROJECT} \
--format="value(httpsTrigger.url)")
cd ./appengine
# Update `app.yaml` environment variable with server endpoint
sed --in-place "s|REPLACE|${SERVER_URL}|g" ./app.yaml
gcloud app deploy \
--project=${PROJECT} \
--quiet
CLIENT_URL=$(\
gcloud app describe \
--project=${PROJECT} \
--format="value(defaultHostname)")
curl --request GET ${CLIENT_URL}
Hello Freddie
package.json
:
{
"name": "65449123",
"version": "0.0.1",
"scripts": {
"start": "node index.js"
},
"dependencies": {
"body-parser": "1.19.0",
"express": "4.17.1",
"json-rpc-2.0": "0.2.12",
"node-fetch": "2.6.1"
}
}
and:
index.js
:
const { JSONRPCClient, createJSONRPCErrorResponse } = require("json-rpc-2.0");
const express = require("express");
const fetch = require("node-fetch");
const SERVER_URL = (() => {
let SERVER_URL = process.env.SERVER_URL
console.log(SERVER_URL);
return SERVER_URL
})();
const client = new JSONRPCClient(
(jsonRPCRequest) =>
fetch(SERVER_URL, {
method: "POST",
headers: {
"content-type": "application/json"
},
body: JSON.stringify(jsonRPCRequest)
}).then(response => {
if (response.status === 200) {
return response.json()
.then(jsonRPCResponse => client.receive(jsonRPCResponse));
} else if (jsonRPCRequest.id !== undefined) {
return Promise.reject(new Error(response.statusText));
}
})
);
const app = express();
app.get("/", (req, res) =>
client.request("echo", { text: "Hello Freddie" }).then(result => {
console.log(result);
res.status(200).send(result);
})
);
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`Listening: ${PORT}`);
})
NOTE App Engine standard
require(express)
and I'm usingnode-fetch
to mirror the NPM example
app.yaml
:
runtime: nodejs12
env_variables:
SERVER_URL: REPLACE
and:
package.json
:
{
"name": "65449123",
"version": "0.0.1",
"dependencies": {
"body-parser": "1.19.0",
"json-rpc-2.0": "0.2.12"
}
}
and:
index.js
:
const bodyParser = require("body-parser");
const { JSONRPCServer } = require("json-rpc-2.0");
const server = new JSONRPCServer();
server.addMethod("echo", ({ text }) => text);
server.addMethod("log", ({ message }) => console.log(message));
exports.server = (req, res) => {
const jsonRPCRequest = req.body;
console.log(JSON.stringify(jsonRPCRequest, null, 2));
server.receive(jsonRPCRequest).then(jsonRPCResponse => {
if (jsonRPCResponse) {
res.json(jsonRPCResponse);
} else {
res.sendStatus(204);
}
});
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.