angular - Angular 6.x / 设置 jsessionid cookie
问题描述
我使用 java 和 springboot 2.x 开发了我的应用程序后端,另一方面,我有我的 Angular 应用程序。我还使用 OAuth2 协议登录,我需要的是在登录 cookie 后保存谷歌提供的 JSESSION id,然后在每个请求中将其发送到后端应用程序。我阅读了有关使用 HttpInterceptor 的信息,但我无法解决。有什么帮助吗?谢谢
解决方案
Angular HTTPInterceptor 是最合适的解决方案。
您可以通过以下步骤使用它:
1:构建您的 HTTPInterceptor(@Injectable 服务):
@Injectable()
export class SpringbootInterceptor implements HttpInterceptor {
constructor(public auth: AuthService) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// Clone the request to add the new header
const clonedRequest = req.clone({ headers: req.headers.set('Set-Cookie', 'jsessionid=' + this.auth.getJSessionId()) });
// Pass control to the next request
return next.handle(clonedRequest);
}
}
请注意,.clone()方法添加作为参数提供的信息。
2:将拦截器设置为您的 NgModule 提供者:
@NgModule({
bootstrap: [AppComponent],
imports: [...],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: SpringbootInterceptor,
multi: true
}
]
})
现在,来自 NgModule 的任何请求,在SpringbootInterceptor中设置标头。
您可以在以下位置查看更多信息:
推荐阅读
- angular - 不确定如何在 Angular 上为自定义组件应用双向绑定
- url - url查询mydomain.com/myscrip.php/word的服务器端处理
- javascript - 为什么使用 useRef 钩子定义的计数器在每次渲染时都不会递增?
- wordpress - 在 Gatsby 中,使用 Wordpress 作为数据源,使用不同的模板创建不同的页面
- azure - OrchestrationTrigger 持久函数:使用 Azure 函数应用程序消耗等待的输入和执行时间
- laravel - Laravel-5.8:路由显示不返回任何值
- nsis - 如何杀死系统托盘图标应用程序?
- testing - Google Cloud Pub/Sub - 发布测试消息
- html - 背景在调整大小时不会填满 div 的整个高度
- android - 如何在 Android 中将 idToken 与 Firebase 一起使用