How to bring a gRPC defined API to the web browser

前端 未结 8 751
孤街浪徒
孤街浪徒 2021-01-29 22:39

We want to build a Javascript/HTML gui for our gRPC-microservices. Since gRPC is not supported on the browser side, we thought of using web-sockets to connect to a node.js serve

相关标签:
8条回答
  • 2021-01-29 23:34

    Looking at the current solutions with gRPC over web, here is what's available out there at the time of writing this (and what I found):

    • gRPC-web: requires TypeScript for client
    • gRPC-web-proxy: requires Go
    • gRPC-gateway: requires .proto modification and decorations
    • gRPC-bus-websocket-proxy-server: as of writing this document it lacks tests and seems abandoned (edit: look at the comments by the original author!)
    • gRPC-dynamic-gateway: a bit of an overkill for simple gRPC services and authentication is awkward
    • gRPC-bus: requires something for the transport

    I also want to shamelessly plug my own solution which I wrote for my company and it's being used in production to proxy requests to a gRPC service that only includes unary and server streaming calls:

    • gRPC-express

    Every inch of the code is covered by tests. It's an Express middleware so it needs no additional modifications to your gRPC setup. You can also delegate HTTP authentication to Express (e.g with Passport).

    0 讨论(0)
  • 2021-01-29 23:39

    An official grpc-web (beta) implementation was released on 3/23/2018. You can find it at

    https://github.com/grpc/grpc-web

    The following instructions are taken from the README:

    Define your gRPC service:

    service EchoService {
      rpc Echo(EchoRequest) returns (EchoResponse);
    
      rpc ServerStreamingEcho(ServerStreamingEchoRequest)
          returns (stream ServerStreamingEchoResponse);
    }
    

    Build the server in whatever language you want.

    Create your JS client to make calls from the browser:

    var echoService = new proto.grpc.gateway.testing.EchoServiceClient(
      'http://localhost:8080');
    

    Make a unary RPC call

    var unaryRequest = new proto.grpc.gateway.testing.EchoRequest();
    unaryRequest.setMessage(msg);
    echoService.echo(unaryRequest, {},
      function(err, response) {
        console.log(response.getMessage());
      });
    

    Streams from the server to the browser are supported:

    var stream = echoService.serverStreamingEcho(streamRequest, {});
    stream.on('data', function(response) {
      console.log(response.getMessage());
    });
    

    Bidirectional streams are NOT supported:

    This is a work in progress and on the grpc-web roadmap. While there is an example protobuf showing bidi streaming, this comment make it clear that this example doesn't actually work yet.

    Hopefully this will change soon. :)

    0 讨论(0)
提交回复
热议问题