简体   繁体   English

Gcloud 未在 nodejs 应用程序中启动 json rpc 客户端

[英]Gcloud is not intiating the json rpc client in nodejs app

I have a nodejs app which is integrating to simplybook.me using jsonrpc.我有一个 nodejs 应用程序,它使用 jsonrpc 集成到 simplebook.me。 the integration is working good on my local server.集成在我的本地服务器上运行良好。 but the client is failed to initialize when I run it over gcloud app.但是当我通过 gcloud 应用程序运行客户端时,客户端无法初始化。

file: index.js: `文件: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文件: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.我已经使用 gcloud app deploy 部署了我的应用程序。

file: app.yaml:文件: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.它在本地运行但不在服务器上运行,是的端口是 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 .我使用 NPM文档构建了一个简单的 gRPC-JSON 示例。

I published the server as a Google Cloud Function and the client as an App Engine (standard) app.我将服务器发布为 Google Cloud Function,将客户端发布为 App Engine(标准)应用。

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

Client客户

package.json : 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 : 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 using node-fetch to mirror the NPM example注意App Engine 标准require(express) ,我正在使用node-fetch来镜像 NPM 示例

Server服务器

app.yaml : app.yaml

runtime: nodejs12

env_variables:
  SERVER_URL: REPLACE

and:和:

package.json : package.json

{
    "name": "65449123",
    "version": "0.0.1",
    "dependencies": {
        "body-parser": "1.19.0",
        "json-rpc-2.0": "0.2.12"
    }
}

and:和:

index.js : 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);
        }
    });
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM