Angular2 在获取资源时观察 302 重定向 [英] Angular2 watch for 302 redirect when fetching resource

查看:19
本文介绍了Angular2 在获取资源时观察 302 重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从我公司持有的另一个域中提取一些资源.我想通过 GET 请求提取安全的 HTML 内容.

I have a requirement to pull a few resources from another domain held by my company. I want to pull secured HTML content with GET requests.

当用户退出应用程序时,请求的内容将向登录页面返回 302.

When a user is signed out of the application the requested content will return a 302 to the login page.

到目前为止,我尝试嗅探 302 的标头还没有返回我所希望的.我的 Observable 返回的响应是 200(登录页面).

My attempts to sniff the headers for a 302 haven't returned what I'd hoped for so far. The response returned by my Observable is a 200 (login page).

这是我的示例应用.

export class MenuComponent implements OnInit {

    private _resourceUrl = "http://localhost:3001/resources/menu";

    constructor(private _http: Http){
    }

    menu: string;

    ngOnInit(): void {
        this.getMenu()
            .subscribe(
                response => {
                    console.log(`Response status: ${response.status}`);

                    this.menu = response.text();
                },
                error => console.log(<any>error));
    }

    getMenu(): Observable<Response>{        
        return this._http.get(this._resourceUrl)
            .map((response: Response) => response)
            .catch(this.handleError);
    }

    private handleError(error: Response){
        console.log(error);
        return Observable.throw(error.json().error || 'Server Error');
    }
}

我是否走在正确的轨道上?

Am I even on the right track?

推荐答案

如果服务器在 Location 标头内发送带有 302 状态代码的重定向,重定向的 URL 将自动处理由浏览器执行,即执行对该 URL 的请求.

If the server sends a redirect with a 302 status code with the URL to redirect within a Location header, the redirect is automatically handled by the browser, i.e. a request to this URL is executed.

这就是为什么 XHR(以及围绕它的 Angular2 包装器,即 Http 类)不会看到第一个请求的结果,而只会看到第二个请求的响应.

That's why XHR (and the Angular2 wrapper around it, i.e. the Http class) won't see the result of the first request but only the response of the second one.

这篇关于Angular2 在获取资源时观察 302 重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆