【问题标题】:How to access request header with Angular2?如何使用 Angular2 访问请求标头?
【发布时间】:2016-08-08 14:41:36
【问题描述】:

在我的 golang 后端成功 oauth2 请求 facebook 后,我将用户重定向到我的应用程序的仪表板,如下所示:

w.Header().Set("Authorization", fmt.Sprintf("Bearer %s", tokenString))
http.Redirect(w, r, "http://" + r.Host + "/dashboard?jwt=" + tokenString, http.StatusFound)

然后在仪表板初始化时,我执行以下操作:

params:RouteParams;


constructor(private _router:Router, private _jwt:JWTService, private _params:RouteParams, private location:Location) {
    this.params = _params;


}


consol() {
    var redirect_url = encodeURIComponent("http://localhost:9000/api/facebook/");
    var url = "https://www.facebook.com/dialog/oauth?client_id=xxxx&redirect_uri="+ redirect_url + "&response_type=code&scope=email+user_location+user_about_me"
    window.location.href=url;
}

ngOnInit() {
    this.token = '';
    console.log(this.params);
    if (this.params.params['jwt'] != null) {
        console.log(this.params);
        localStorage.setItem('jwt', this.params.params['jwt']);
        this.location.replaceState('/dashboard')
    }
    this.Bouncer();
}

我想避免弄脏我的网址,哪怕只有几秒钟。我希望我可以检查请求标头,因为我也通过它发送 jwt。

更新

原始请求是通过 angular2-material 按钮完成的

 <div md-raised-button color="warn" (click)="consol()">Login to FACEBOOK</div>

【问题讨论】:

  • 如果它是您要查找的第一个请求(打开页面的请求)的标头,您将无法找到它们。请在此处查看此问题以获取更多信息。 stackoverflow.com/questions/220231/…
  • 我想要刚刚发布的重定向的标头。这是一样的吗? @toskv
  • 请求重定向是通过javascript还是浏览器完成的?
  • 通过我的 golang 后端。线条在顶部
  • 后端重定向请求,该请求来自事务。如果请求来自浏览器(例如用户导航),那么您将无法访问它。如果它来自js,你也许可以。查看 TypeScript 代码,虽然它看起来是启动应用程序的请求,因此无法访问它的标头。

标签: go typescript angular jwt


【解决方案1】:

首先我创建一个弹出窗口/选项卡。

    var url = "https://accounts.google.com/o/oauth2/auth?client_id="
                    + clientid + "&redirect_uri="
                    + redirect_url + "&response_type=code&scope="
                    + scope;
    window.open(url);

这会转到谷歌并在返回的路上点击我的服务器,在重定向 url 上。 它在此弹出窗口内提供下面的脚本标记。它实际上只是在创建此弹出窗口的窗口上运行一个命令,在本例中是我的 SPA,将我的应用程序令牌作为参数,然后将其关闭。

w.Write([]byte(`
                    <script>
                        var token="` + token + `";
                        function CloseMySelf() {
                            try {
                                window.opener.angularComponentRef.runThisFunctionFromOutside(token);
                            }
                            catch (err) {}
                            window.close();
                            return false;
                        }
                        CloseMySelf();
                    </script>

    `))

这是它调用的函数。这个方法需要像question这样公开。

runThisFunctionFromOutside(token) {
    localStorage.setItem('jwt', token);
    location.href = "../dashboard";
}

【讨论】:

    猜你喜欢
    • 2014-02-15
    • 1970-01-01
    • 2022-11-10
    • 2018-11-13
    • 1970-01-01
    • 2015-10-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多