- 使用http协议进行前后端交互,后端使用http到rpc协议进行转发:https://github.com/lilinxi/pilipili
- 使用thrift或protobuf等序列化协议构造restful-api:https://www.jianshu.com/p/f084ea37e419
- 使用nginx或envoy等代理服务器转发,仅限gRPC-web
- envoy转发:https://github.com/grpc/grpc-web/tree/master/net/grpc/gateway/examples/helloworld
- nginx转发:https://segmentfault.com/a/1190000022022271
- 直接使用rpc框架生成的js-client,使用node,vue或react
nginx 转发 gRPC-web:
server {
listen 8199;
server_name _;
access_log /tmp/grpc.log;
error_log /tmp/grpc.log debug;
location ~ \.(html|js)$ {
root /var/www/html;
}
location / {
# 重点!!需要将Content-Type更改为 application/grpc
# grpc-web过来的是application/grpc-web+proto || application/grpc-web+text (取决于生成js代码时grpc-web_out 的mode选项,本文用grpcweb 则为application/grpc-web+proto)
grpc_set_header Content-Type application/grpc;
grpc_pass localhost:9999;
# 因浏览器有跨域限制,这里直接在nginx支持跨域
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Transfer-Encoding,Custom-Header-1,X-Accept-Content-Transfer-Encoding,X-Accept-Response-Streaming,X-User-Agent,X-Grpc-Web';
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain charset=UTF-8';
add_header 'Content-Length' 0;
return 204;
}
if ($request_method = 'POST') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Transfer-Encoding,Custom-Header-1,X-Accept-Content-Transfer-Encoding,X-Accept-Response-Streaming,X-User-Agent,X-Grpc-Web';
add_header 'Access-Control-Expose-Headers' 'Content-Transfer-Encoding, grpc-message,grpc-status';
}
}
}