i'm trying to create an app using Angular2 as the frontend and cakephp 3 as the REST Api, the authentication works fine, but when i try to acces any other url i get the 401 Unauthorized status, and i noticed that the Request Method is OPTIONS instead of GET that i used in my code, and the Authorization header with my token is not sent to the server:
Here's my user.service.ts code:
constructor(private http: Http,
private router: Router,
) { }
login(email: string, password: string){
let headers: Headers = new Headers({ 'Accept': 'application/json','Content-Type': 'application/json' });
let options: RequestOptions = new RequestOptions({headers: headers});
return this.http.post('http://www.students.com/api/users/token.json', {email: email, password: password}, options)
.map((data: Response)=> data.json())
.subscribe(
(data)=> this.handlData(data),
(error)=> this.handlError(error)
);
}
getSessionData(){
let token = localStorage.getItem('usr_token');
let headers = new Headers({ 'Accept': 'application/json', 'Authorization': 'Bearer ' + token });
let options: RequestOptions = new RequestOptions({headers: headers});
return this.http.get('http://www.students.com/api/users/getSessionData', options).subscribe(
data => console.log(data),
err => console.log(err)
);
}
handlData(data){
if(data.success){
let usrData = data.data.user;
this.user = new User(usrData.email, usrData.firstname, usrData.lastname, usrData.role, data.data.token);
localStorage.setItem('id_token', data.data.token);
}
}
handlError(error){
console.log(error);
}
i tried to use angular2-jwt module but i had the same error, and to make sure that my API works fine, i tested it with Postman chrome extension and it worked as expected:
and here's my Apache2 VirtualHost configuration
<VirtualHost *:80>
ServerAdmin webmaster@localhost
DocumentRoot /var/www/html/students
ServerName www.students.com
<Directory /var/www/html/students>
Require all granted
Options Indexes FollowSymLinks Includes
AllowOverride all
</Directory>
Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS"
Header always set Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept, Authorization"
</VirtualHost>
any one had the same problem? any ideas why is that happening?