我正在使用Angular 2作为Front end&在Cakephp 3的后端。我正在尝试登录时获得401 Unauthorized状态。我在cakephp 3中配置了JWT,它在POSTMAN中工作正常。但不与Angular合作。
这是我的TypeScript代码
loginToken(uname: string, pwd: string): Observable<boolean>{
let json = JSON.stringify({ username: uname , password: pwd});
let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Accept', 'application/json');
let options = new RequestOptions({ headers: headers });
return this.http.post('http://localhost/crm/crm/api/users/token', json, options)
.map((response: Response) => {
let token = response.json() && response.json().token;
if (token) {
this.token = token;
localStorage.setItem('currentUser', JSON.stringify({ username: uname, token: token }));
return true;
} else {
return false;
}
});
}
Cakephp 3代码 - 服务器端
public function token()
{
$user = $this->Auth->identify();
if (!$user) {
throw new UnauthorizedException('Invalid username or password');
}
$this->set([
'success' => true,
'data' => [
'token' => JWT::encode([
'sub' => $user['id'],
'exp' => time() + 604800
],
Security::salt())
],
'_serialize' => ['success', 'data']
]);
}
删除选项后 -
loginToken(uname: string, pwd: string): Observable<boolean>{
let json = JSON.stringify({ username: uname , password: pwd});
let headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
let options = new RequestOptions({ headers: headers });
return this.http.post('http://localhost/crm/crm/api/users/token', json, {headers: headers })
.map((response: Response) => {
let token = response.json() && response.json().token;
if (token) {
this.token = token;
localStorage.setItem('currentUser', JSON.stringify({ username: uname, token: token }));
return true;
} else {
return false;
}
});
}
我的反应
答案 0 :(得分:1)
您的问题丢失或内容类型标题错误。
要登录不发送OPTIONS请求,您的内容类型应为标准表单类型之一: application / x-www-form-urlencoded或multipart / form-data
我认为,文字/痛苦也可能有用,但我自己并没有使用它。
编辑:实际上有一个关于它的SO:How to disable OPTIONS request?