10

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

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

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

这是我的示例应用程序。

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');
    }
}

我什至走在正确的轨道上吗?

4

2 回答 2

22

如果服务器发送带有 302 状态代码的重定向,并且在Location标头中包含要重定向的 URL,则该重定向将由浏览器自动处理,即执行对该 URL 的请求。

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

于 2016-04-27T09:28:34.357 回答
0

这是我重定向到 ServiceData 的工作代码。Angular2(4) 和 ASP 网络核心。

private post(url: string, data?: any) {
    return this.http.post(url, data, { headers: this.headers })
      .map(response => this.extractData(response, true));
}

private extractData(res: Response, mapJson = true) {
    let body: any = res;
    // redirect
    if (body.url.search('ReturnUrl') != -1) {
        let url = new URL(body.url);

        // get patch redirect simple /account/login
        let pathname = url.pathname;

        // get params redirect simple ?ReturnUrl=%2Fapi%2Fitems%2FGetitems
        let search = url.search;

        // 1 navigate with params
        this.router.navigate.navigate([pathname], { queryParams: { returnUrl: search } });

        // OR ...

        // 2 navigate only pathname
        this.router.navigate.navigate([pathname]);
        return {};
    }            

    if (mapJson) {
        body = body.json();
    }
    return body || {};
}
于 2017-08-25T05:17:46.880 回答