要解决Nest.js谷歌OAuth重定向问题中的CORS错误,可以尝试以下解决方法。
在main.ts
文件中添加以下代码:
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { NestExpressApplication } from '@nestjs/platform-express';
import { CorsOptions } from '@nestjs/common/interfaces/external/cors-options.interface';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
// 添加CORS中间件
const corsOptions: CorsOptions = {
origin: true,
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
preflightContinue: false,
optionsSuccessStatus: 204,
credentials: true,
};
app.enableCors(corsOptions);
await app.listen(3000);
}
bootstrap();
这将允许来自所有源的请求,并在响应上设置Access-Control-Allow-Origin
标头。
确保在谷歌开发者控制台中为您的应用程序正确配置了重定向URL。这应该是您Nest.js应用程序的URL,以及用于处理谷歌OAuth回调的路径。
在谷歌开发者控制台中,确保已启用CORS(跨域资源共享)设置。这将允许您的Nest.js应用程序跨域接收来自谷歌身份验证服务器的响应。
在您的代码中,确保正确配置了谷歌OAuth策略。确保您提供了正确的客户端ID、客户端密钥和重定向URL。
import { PassportStrategy } from '@nestjs/passport';
import { Strategy } from 'passport-google-oauth20';
@Injectable()
export class GoogleStrategy extends PassportStrategy(Strategy, 'google') {
constructor(private readonly authService: AuthService) {
super({
clientID: 'your-client-id',
clientSecret: 'your-client-secret',
callbackURL: 'your-callback-url',
scope: ['email', 'profile'],
});
}
async validate(accessToken: string, refreshToken: string, profile: any) {
// 处理验证逻辑
return profile;
}
}
请确保替换正确的客户端ID、客户端密钥和重定向URL。
这些解决方法应该能够解决Nest.js谷歌OAuth重定向问题中的CORS错误。