Angular 4,XHR加载失败:POST

时间:2017-10-20 13:17:45

标签: angular asp.net-web-api2

我已按照本文开发基于令牌的经过身份验证的后端服务:

http://bitoftech.net/2014/06/01/token-based-authentication-asp-net-web-api-2-owin-asp-net-identity/

这一切都按预期工作,我可以使用winforms应用程序进行身份验证,使用c#中的restsharp检索令牌没有问题。现在我来使用Angular 4来开发Web前端,我正在尝试修改它:

http://jasonwatmore.com/post/2016/08/16/angular-2-jwt-authentication-example-tutorial

使用此代码从我的后端获取令牌:



 login(username: string, password: string): Observable<boolean> {

        let data = "grant_type=password&username=" + username + "&password=" + password;

        let headers  = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
        //headers.append('Accept', 'application/json');

        let options = new RequestOptions({headers: headers});

        return this.http.post('http://localhost:61814/token', data, options)
        .map((response: Response) => {
            // login successful if there's a jwt token in the response
            let user = response.json();
            if (user && user.token) {
                // store user details and jwt token in local storage to keep user logged in between page refreshes
                localStorage.setItem('currentUser', JSON.stringify(user));
            }
        
            return user;
        })
        
    }
&#13;
&#13;
&#13;

&#13;
&#13;
login() {
        this.loading = true;
        this.authenticationService.login(this.model.username, this.model.password)
            .subscribe(
                data => {
                    this.router.navigate([this.returnUrl]);
                },
                error => {
                    this.alertService.error(error);
                    this.loading = false;
                });
    }
&#13;
&#13;
&#13;

但是当我在chrome devtools中调试时没有任何反应,网络选项卡中没有任何内容,只有XHR加载失败:POST&#34;在控制台中。

对前端开发很新,并且真的很难与之斗争!

2 个答案:

答案 0 :(得分:1)

如果您的后端项目是一个单独的项目,并且在 http:\ localhost:61814 中运行的api项目,并且您的前端项目是在 http:\ localhost:4200 中运行的角度项目,您的问题是针对此问题的跨源资源共享(CORS)您必须在角度内进行 proxy.config.json 项目并放入此代码:

{
    "/api/*": {
        "target": "http://localhost:61814",
        "secure": false,
        "logLevel": "debug"
    }
}

然后将此文件影响到用于运行动态项目的角度项目

  

npm start(而不是ng serve)

答案 1 :(得分:1)

如果您的后端API项目在 http:\ localhost:61814 上运行,那么您需要设置CROS(跨源资源共享)过滤器,如果您在标头中发送带有密钥授权<的标记/强>

response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with, authorization, cache-control");
response.setHeader("Access-Control-Expose-Headers", "Authorization");

在登录(用户名:字符串,密码:字符串)服务功能应该......

enter code herelogin(username: string, password: string): Observable<boolean> {

    let data = "grant_type=password&username=" + username + "&password=" + password;

    let headers = new Headers();
    headers.append('Content-Type', 'application/json');

    let options = new RequestOptions({headers: headers});

    return this.http.post('http://localhost:61814/token', data, options)
     .map((response: Response) => {
            // login successful if there's a jwt token in the response
            return response;
        });

}

并登录()函数

login() {
    this.loading = true;
    this.authenticationService.login(this.model.username, this.model.password)
        .subscribe(
            data => {
            let token = data.headers.get('Authorization')
            //console.log(this.token)
            // store username and jwt token in local storage to keep user logged in between page refreshes
            sessionStorage.setItem('token', token);

                this.router.navigate([this.returnUrl]);
            },
            error => {
                this.alertService.error(error);
                this.loading = false;
            });
}