我是 NestJS 的新手。我想让我的服务与第三方 API 连接。当我尝试调用 API 时,它总是返回 201 Created,而 http 正文中没有结果,
这是我的服务,
@Injectable()
export class AuthService {
constructor(
private readonly httpService: HttpService,
private configService: ConfigService
) {}
authWithHrService(authDto:AuthDto): Observable<any> {
const host = this.configService.get<string>('HR_HOST');
const port = this.configService.get<string>('HR_PORT');
return this.httpService.post(`${host}:${port}/hr/authen`, authDto).pipe(
map(response => response.data)
);
}
}
这是我的控制器(总是返回 201),
@Controller('auth')
export class AuthController {
private readonly logger = new Logger();
constructor(private readonly authService: AuthService) {}
@Post('')
authen(@Body() req: AuthDto) {
this.authService.authWithHrService(req).subscribe({
next: (data) => {
this.logger.log(`---> authResult :: ${JSON.stringify(data)}`); //This log show result successfully.
return data;
},
error: (err) => {
throw new HttpException("Authentication Failed.", HttpStatus.UNAUTHORIZED);
}
});
}
}
基于Controller,即使结果出现错误,它仍然返回201 Created而不是401
请帮忙。
您不会从控制器返回任何内容,并且不使用特定于库的方法,因此 Nest 将看到方法调用成功。如果您希望 Nest 等待,请返回可观察值(而不订阅它),或者如果您想自己继续订阅,则注入
@Res()
并自行处理发送 res.status().send()
Post
请求始终返回 201
响应代码。
此外,默认情况下响应的状态代码始终为 200,除了使用 201 的 > POST 请求
您可以使用
@HttpCode
装饰器更改此默认行为:
import { HttpCode, HttpStatus } from '@nestjs/common';
// ...rest of your code
@Controller('auth')
export class AuthController {
@Post('')
@HttpCode(HttpStatus.OK)
authen(@Body() req: AuthDto) {
// your request body
}
}
其次,你不必订阅来处理
Observable
。您可以从控制器返回它。
@Post('')
authen(@Body() req: AuthDto) {
return this.authService.authWithHrService(req);
}
如果您想返回自定义错误,可以将代码更改为:
@Post('')
async authen(@Body() req: AuthDto) {
try {
const data = await this.authService.authWithHrService(req).toPromise();
this.logger.log(`---> authResult :: ${JSON.stringify(data)}`);
return data;
} catch (err) {
throw new HttpException("Authentication Failed.", HttpStatus.UNAUTHORIZED);
}
}