代码之家  ›  专栏  ›  技术社区  ›  nagy.zsolt.hun

角度-如何处理重定向

  •  0
  • nagy.zsolt.hun  · 技术社区  · 8 年前

    我使用spring security,它将未经验证的用户重定向到登录页面。

    因此,当未经身份验证的角度客户机向端点发送GET请求(预期为JSON)时,它将接收登录页的HTML内容,而JSON解析器将失败( Angular2 watch for 302 redirect when fetching resource )

    const httpObservable = this.http.get(urlThatWillRedirect).subscribe(data => ...) // JSON parser will fail
    

    如何处理角度重定向?

    3 回复  |  直到 8 年前
        1
  •  3
  •   TtT23    8 年前

    这个 正确的解决方案 是将服务器端代码更改为不返回302状态代码,因为浏览器在Angular(或任何SPA)可以对此做任何事情之前启动重定向通常,你会为此目的返回401/403。

    如果这是不可能的,唯一的选择是实现一个黑客解决方案,以某种方式认识到响应确实是一个重定向,并通过使用httpinterceptors适当地处理它。下面是 AngularJS .

    角度为2+, you could probably follow something like this 要检查响应是否为重定向页,请执行以下操作:

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(req)
          .do(event => {
            if (event instanceof HttpResponseBase) {
              const response = event as HttpResponseBase;
              if (response && response.ok && response.url && response.url.toLowerCase().indexOf(this.logoPartialUrl) >= 0) {
                // Modify this portion appropriately to match your redirect page
                const queryStringIndex = response.url.indexOf('?');
                const loginUrl = queryStringIndex && queryStringIndex > 0 ? response.url.substring(0, queryStringIndex) : response.url;
                console.log('User logout detected, redirecting to login page: %s', loginUrl);
                window.location.href = loginUrl;
              }
            }
          });
    
        2
  •  0
  •   Bernhard    8 年前

    它不是很干净,我建议使用 Router Guards 是的。但是如果JSON解析器失败(这是 未登录 您可以使用错误处理程序在客户端处理重定向。

    const httpObservable = this.http
                                    .get(urlThatWillRedirect)
                                    .subscribe(
                                      (data) => {//handle data},
                                      (error) => {// redirect to login page}          
                                    ); 
    
        3
  •  0
  •   Ganesh    8 年前

    将网页重定向到 error 如有异常 service response 代码。您可以通过在 service 类并将其添加到 catch 属于 Observable 回应。或许我们会处理401或403的这种反应 @I46角 说也试着改变错误代码

       public serviceMethod(){
               this.http.get(urlThatWillRedirect).catch(this.handleError).subscribe(data =>...);
          }
    
    
       private handleError(error:any){
               if(error.code == 302 || error.code == 401){
               // clear your user credentials here like localStorage,Auth token etc..
               window.location.href = '/#/error';
               return Observable.throw(error.json());
              }
            }
    
    推荐文章