使用Axios的NestJS HTTPModule发送HTTPS Get请求始终返回400错误
问题排查与解决
核心原因:请求头缺失
GitHub API要求请求必须包含合法的User-Agent头,Postman会自动添加这类标准请求头,但NestJS的HttpService默认Axios配置未设置该字段,导致GitHub服务器返回400错误。
解决方法
修改app.service.ts中的请求代码,显式添加User-Agent请求头:
import { HttpService } from '@nestjs/axios'; import { Injectable } from '@nestjs/common'; import { AxiosResponse } from 'axios'; import { Observable } from 'rxjs'; @Injectable() export class AppService { constructor(private readonly httpService: HttpService) {} getGithubDetails(): Observable<AxiosResponse> { return this.httpService.get('https://api.github.com/users/bwizrd', { headers: { 'User-Agent': 'NestJS-App' // 可替换为你的应用名称或自定义标识 } }); } }
额外排查方向
- 代理配置检查:若服务运行在需要代理的环境中,Postman可能已配置代理,但Axios未同步设置,需在
HttpService请求配置中添加代理参数。 - SSL证书验证:部分环境下Axios对SSL证书验证更严格,可临时禁用验证(仅用于排查,生产环境禁止):
return this.httpService.get('https://api.github.com/users/bwizrd', { httpsAgent: new (require('https').Agent)({ rejectUnauthorized: false }), headers: { 'User-Agent': 'NestJS-App' } });
内容的提问来源于stack exchange,提问作者Bwizard
相关产品推荐
相关产品推荐

