我正在尝试使用Angular2作为前端和cakephp 3创建一个应用程序作为REST Api,身份验证工作正常,但当我尝试访问任何其他网址时,我得到 401 Unauthorized 状态,我注意到我的代码中使用的请求方法是 OPTIONS 而不是 GET ,而我的令牌的授权标头是没有发送到服务器:
这是我的user.service.ts代码:
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);
}
我尝试使用 angular2-jwt 模块,但我遇到了同样的错误,为了确保我的API工作正常,我使用Postman chrome扩展程序对其进行了测试,并按预期工作:
这是我的Apache2 VirtualHost配置
<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>
任何人都有同样的问题?任何想法为什么会发生这种情况?
答案 0 :(得分:3)
这不是Angular的问题,而是你的后端问题。 Angular正在尝试通过检查服务器是否在OPTIONS请求上返回OK来进行预检请求。您应该设置后端以响应200或204的OPTIONS请求。
如果您使用的是node.js:
app.use('/api', (req, res, next) => {
/** Browser check for pre-flight request to determine whether the server is webdav compatible */
if ('OPTIONS' == req.method) {
res.sendStatus(204);
}
else next();
});
或laravel(PHP):
App::before(function($request)
{
// Sent by the browser since request come in as cross-site AJAX
// The cross-site headers are sent via .htaccess
if ($request->getMethod() == "OPTIONS")
return new SuccessResponse();
});
这将告诉浏览器服务器可以正确处理webdav请求方法。
提问者在CakePHP上添加更新::
public function initialize() {
parent::initialize();
if($this->request->is('options')) {
$this->response->statusCode(204);
$this->response->send();
die();
}
$this->Auth->allow(['add', 'token']);
}