【问题标题】:NestJS gRPC empty returnNestJS gRPC 空返回
【发布时间】:2021-10-19 23:44:15
【问题描述】:

我正在学习有关 NestJS 和 gRPC 的新知识。我只是遇到了一个问题。我创建了一个身份验证微服务和一个网关,但我得到一个空响应。

网关和微服务被触发。但我得到了一个空对象。如果我在没有 gRPC 的网关中进行硬编码,那么它可以工作。有谁知道我忘记了什么?

网关

import { Body, Controller, OnModuleInit, Post } from '@nestjs/common';
import { Client, ClientGrpc } from '@nestjs/microservices';
import { authOptions } from 'src/grpc.options';
import { AuthService } from './grpc.interface';

@Controller('auth')
export class AuthController implements OnModuleInit {
    @Client(authOptions)
    private client: ClientGrpc;

    private authService: AuthService;

    onModuleInit() {
        this.authService = this.client.getService<AuthService>('AuthService');
    }

    @Post('login')
    async login(@Body('username') username: string, @Body('password') password: string)
    {
        return this.authService.login({ username, password });
    }
}

身份验证微服务

import { Controller } from '@nestjs/common';
import { GrpcMethod } from '@nestjs/microservices';

interface LoginArgs {
    username: string;
    password: string;
}

interface LoginReturn {
    access_token: string;
}

@Controller('auth')
export class AuthController {

    @GrpcMethod('AuthService', 'Login')
    login(data: LoginArgs, metadata: any): LoginReturn
    {
        return {
            access_token: '123',
        }
    }

}

原型

syntax = "proto3";

package auth;

service AuthService {
    rpc Login (LoginArgs) returns (LoginReturn);
}

message LoginArgs {
    string username = 1;
    string password = 2;
}

message LoginReturn {
    string access_token = 1;
}

【问题讨论】:

    标签: nestjs grpc


    【解决方案1】:

    当字段名包含下划线时,gRPC Client 不发送字段。

    您应该删除 access_token 中的所有下划线,然后才能工作。

    或将以下 keepCase: true 添加到连接选项(如 here 所述)

    app.connectMicroservice<MicroserviceOptions>({
        transport: Transport.GRPC,
        options: {
          package: 'test',
          protoPath: 'path/to/proto',
          loader: { keepCase: true },
        },
      });
    

    【讨论】:

      猜你喜欢
      • 2020-09-27
      • 2021-12-10
      • 2021-08-08
      • 1970-01-01
      • 1970-01-01
      • 2021-03-09
      • 2018-10-28
      • 2020-07-01
      • 1970-01-01
      相关资源
      最近更新 更多