grpc / grpc-web

gRPC for Web Clients
https://grpc.io
Apache License 2.0
8.45k stars 760 forks source link

> It's working for grpc-web + protobuf.js. I hope it helps somebody. #1410

Closed rmv9490 closed 2 weeks ago

rmv9490 commented 3 months ago
          > It's working for grpc-web + protobuf.js. I hope it helps somebody.
import { ChunkParser, ChunkType } from "grpc-web-client/dist/ChunkParser"
import { RPCImpl } from "protobufjs";

function rpcImpl(serviceName: string): RPCImpl {
    return async (method, requestData, callback) => {
        const request = await fetch(`${BASE_URL}/${serviceName}/${method.name}`, {
            method: "POST",
            headers: {
                "content-type": "application/grpc-web+proto",
                "x-grpc-web": "1",
            },
            body: frameRequest(requestData),
        });
        const buffer = await request.arrayBuffer();
        const chunk = parseChunk(buffer);

        callback(null, chunk && chunk.data ? new Uint8Array(chunk.data) : null);
    };
}

function parseChunk(buffer: ArrayBuffer) {
    return new ChunkParser()
        .parse(new Uint8Array(buffer))
        .find(chunk => chunk.chunkType === ChunkType.MESSAGE);
}

function frameRequest(bytes: Uint8Array) {
    const frame = new ArrayBuffer(bytes.byteLength + 5);
    new DataView(frame, 1, 4).setUint32(0, bytes.length, false);
    new Uint8Array(frame, 5).set(bytes);
    return new Uint8Array(frame);
}

Getting Failed to parse URL, Browser is not able to parse the URL

Fetch error: TypeError: Failed to execute 'fetch' on 'Window': Failed to parse URL from http://10.81.200.09:8000/loginService_package.LoginService/LoginMethod at zone.js:1505:1 at proto. (zone.js:973:1) at LoginService. (app.component.ts:41:31) at Generator.next () at asyncGeneratorStep (asyncToGenerator.js:3:1) at _next (asyncToGenerator.js:25:1) at asyncToGenerator.js:32:1 at new ZoneAwarePromise (zone.js:1427:1) at LoginService. (asyncToGenerator.js:21:1) at LoginService.rpcImpl (app.component.ts:36:5)

Can someone please help in resolving this?
Many Thanks in advance

Originally posted by @rmv9490 in https://github.com/grpc/grpc-web/issues/80#issuecomment-1987124711

sampajano commented 3 months ago

Thanks for re-posting the question!

FYI, murgatroid99@ provided a reply at: https://github.com/grpc/grpc-web/issues/80#issuecomment-1989010546

Is that helpful to you?

Thanks!

sampajano commented 2 weeks ago

Closing due to inactivity. Feel free to re-open and follow up later if there are more updates. Thanks!