首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Angular5 Auth令牌

Angular5 Auth令牌
EN

Stack Overflow用户
提问于 2018-04-13 19:38:18
回答 2查看 463关注 0票数 1

我正在致力于连接角前端,以便与API后端通信。我要做的第一件事是完成登录。我正试图将令牌放入本地存储库,但我不知道哪里出了问题。我一直收到一个400错误的网关错误。

auth.service console.log(res)在后台返回我希望从api中得到的json响应。

代码语言:javascript
运行
复制
@Injectable()
export class AuthService {

  private BASE_URL: string = 'http://127.0.0.1:8000/rest-auth';
  private headers: HttpHeaders = new HttpHeaders({'Content-Type': 'application/json'});

  constructor(private http: HttpClient) {}

  login(user: LoginReponse): Promise<any> {
    let url: string = `${this.BASE_URL}/login/`;

    let headers = new Headers({
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    });
    return this.http.post(url, user, {headers: this.headers}).toPromise()
      .then(
        res => console.log(res)
      );
  }

login.component

代码语言:javascript
运行
复制
@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent {
  private TOKEN_KEY = 'id_token';
  public loginResponse: any = new LoginReponse()

  constructor(
    private auth: AuthService,
    private router: Router
  ) {

  }

  onLogin(): void {
    console.log('log user');
    this.auth.login(this.loginResponse)
      .then((loginResponse) => {
        localStorage.setItem('token', loginResponse.data.token);
        console.log('got past localstorage');
      })
      .catch((err) => {
        // console.log(err);
        console.log();
      });
  }
}

代码语言:javascript
运行
复制
export class LoginReponse {
  token: string;
  user: {
    pk: number;
    username: string;
    email: string;
    first_name: string;
    last_name: string;
  };
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-04-13 19:47:22

我也有同样的问题。请看一下herehere。在那里,你会发现我是如何解决飞行前请求的问题的,以及我是如何设置我的角5应用程序来使用令牌的。

如果您需要更多的帮助,请告诉我。

票数 2
EN

Stack Overflow用户

发布于 2018-04-14 02:56:36

我建议查看后端setup.Certain“跨域”请求(特别是Ajax请求)上的CORS设置,该策略默认禁止相同来源的安全策略,这可能导致http 400错误。

我还将提供auth保护和服务示例代码,它使用的是可观察的对承诺的承诺,现在可观察的可能是比诺言的更好的选择。

AUTH警卫

代码语言:javascript
运行
复制
import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';

import { AuthService } from './auth.service';
import {Observable} from "rxjs";

@Injectable()
export class AuthGuard implements CanActivate {
    constructor(private router: Router, private user: AuthService) {}

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        // check to see if a user has a valid jwt
        if (this.user.isLoggedIn()) {
            return true; // allows user to load home component
        }

        //if not, redirect back to login page
        this.router.navigate(['/login']);
        return false;
    }
}

AUTH SERVICE

代码语言:javascript
运行
复制
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';

import { HttpClientModule } from '@angular/common/http';

@Injectable()
export class AuthService {
    private errorMessge: string;

    constructor(private http: HttpClientModule, private router: Router){}

    isLoggedIn(){
        return !!localStorage.getItem('token')
    }

    logout(){
        localStorage.removeItem('token');
        this.router.navigate(['login']);
    }

    login(email: string, password: string){
        let body = { email: email, password: password };
        this.http
            .post('/auth/login', body)
            .subscribe(
                res => {
                    localStorage.setItem('token', res.token);
                    this.router.navigate(['home/profile']);
                },
                error => {
                    console.log(error);
                    this.errorMessge = error.message;
                }
            );
    }

}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49824033

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档