我正在研究角度前端的连接,以便与API后端进行通信。我要做的第一件事是完成登录身份验证。我试图将令牌设置为本地存储,我不知道我哪里出错了。我一直收到400错误的网关错误。
auth.service console.log(res)会返回我期望从api获得的json响应。
raven.js:1 Hook failure
1. {type: "system", message: "unexpected end of JSON input", fields: Array(0)}
1. fields:[]
2. message:"unexpected end of JSON input"
3. type:"system"
4. __proto__:Object
raven.js:1 Error(s) triggering preview hook
1. [{…}]
console.(anonymous function) @ raven.js:1
(anonymous) @ installs.coffee:53
processQueue @ angular.js:13318
(anonymous) @ angular.js:13334
$eval @ angular.js:14570
login.component
@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)
);
}
类
@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();
});
}
}
答案 0 :(得分:2)
答案 1 :(得分:0)
我建议您在后端设置中查看您的CORS设置。明确&#34;跨域&#34;默认情况下,同源安全策略禁止请求,特别是Ajax请求,这可能导致http 400错误。
我还将提供使用Observable对Promises的auth guard和服务示例代码,现在Observable可能是比Promise更好的选择。
AUTH GUARD
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;
}
);
}
}