我正在致力于连接角前端,以便与API后端通信。我要做的第一件事是完成登录。我正试图将令牌放入本地存储库,但我不知道哪里出了问题。我一直收到一个400错误的网关错误。
auth.service console.log(res)在后台返回我希望从api中得到的json响应。
@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
@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();
});
}
}
类
export class LoginReponse {
token: string;
user: {
pk: number;
username: string;
email: string;
first_name: string;
last_name: string;
};
}
发布于 2018-04-13 19:47:22
发布于 2018-04-14 02:56:36
我建议查看后端setup.Certain“跨域”请求(特别是Ajax请求)上的CORS设置,该策略默认禁止相同来源的安全策略,这可能导致http 400错误。
我还将提供auth保护和服务示例代码,它使用的是可观察的对承诺的承诺,现在可观察的可能是比诺言的更好的选择。
AUTH警卫
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
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;
}
);
}
}
https://stackoverflow.com/questions/49824033
复制相似问题