基于Angular 4令牌的身份验证

时间:2017-11-12 19:05:51

标签: angular typescript authentication token

当我发布用户名和密码时,我需要回复我。当我使用get方法获取该标记时,我需要从URL返回数据。但错误是 http://tcmtestapi.azurewebsites.net/api/demo/inventory:预检的响应包含无效的HTTP状态代码405。

@Component({
  selector: 'app-envanter',
  templateUrl: './envanter.component.html',
  styleUrls: ['./envanter.component.css'],
  encapsulation: ViewEncapsulation.None
})
export class EnvanterComponent implements OnInit {
  userName= 'tcmtest';
  password= '123456';
  token : string;
  error: any;
  envanterList: any;

  constructor(private envanterService: EnvanterService) { }

  ngOnInit() {
    this.envanterService.login(this.userName, this.password);
    this.envanterList = this.envanterService.getEnvanterList(this.token)
    .subscribe(
      envanterList => this.envanterList = envanterList,
      error => this.error = error
    );
  }

}

@Injectable()
export class EnvanterService {
  public token: string;

  constructor(private http: Http) {
    this.token = localStorage.getItem('token');
    this.http = http;

  }
  login(userName: string, password: string): Observable<any> {
    let url = `http://tcmtestapi.azurewebsites.net/api/demo/token`;
    let body = JSON.stringify({userName,password});
    let headers = new Headers({ 'Content-Type': 'application/json; charset=UTF-8' });
    let options = new RequestOptions({ headers: headers });

    return this.http.post(url, body, options)
      .map((res: any) => {
        let data = res.json();
        this.token = data.token;
        return this.token; 
      });

  }

  getEnvanterList(token) {
    this.token = token;
    let url = `http://tcmtestapi.azurewebsites.net/api/demo/inventory`;
    let headers = new Headers({'Authorization': 'Bearer ' + this.token});
    let options = new RequestOptions({ headers: headers });
    return this.http.get(url,options)
      .map((response: Response) => response.json())
  }
}

1 个答案:

答案 0 :(得分:0)

您是否在API中启用了CORS?如果您已启用它,请添加withCredentials : true,如下所示:

this.options = new RequestOptions({ headers: this.headers, withCredentials : true });