我在后端使用Laravel 5.7
,在前端使用Tymon\JWTAuth 1.0.0-rc3
,在前端使用Angular 7
。我使用以下PHP代码:
public function login(Request $request)
{
$credentials = $request->only('email', 'password');
try {
// attempt to verify the credentials and create a token for the user
if (! $token = JWTAuth::attempt($credentials)) {
return response()->json(['error' => 'invalid_credentials'], 401);
}
} catch (JWTException $e) {
// something went wrong whilst attempting to encode the token
return response()->json(['error' => 'could_not_create_token'], 500);
}
// all good so return the token
return response()->json(compact('token'));
}
此代码来自Tymon的JWTAuth文档的原始文档作为示例代码。
我在Postman
中创建了一个实例,以使用以下选项测试此代码:
标题:
内容类型:application / json
身体
:{
"email": "admin@admin.test",
"password": "admin"
}
每个人都工作正常。我以正确的格式返回令牌,如下所示:
{
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.ey....EifQ.nMr5Q1mX9O-3dknpNRBjOiOc1QJjEJydaOJOVqNFfWc"
}
然后我尝试在Angular中使用以下代码:
export class AuthService {
constructor(private http: Http) { }
login(credentials: any) {
const headers = new Headers();
headers.append('Content-Type', 'application/json');
const options = new RequestOptions({ headers: headers });
return this.http.post(
'/api/auth/login',
JSON.stringify(credentials)
)
.pipe(map(response => {
const result = response.json();
if (result && result.token) {
localStorage.setItem('token', result.token);
return true;
}
return false;
}));
}
// ...
}
这会返回此错误消息:
{_body: "{"error":"invalid_credentials"}", status: 401, ok: false, statusText: "Unauthorized", headers: Headers, ...}
已检查URL,两种情况都相同。用户名和密码已检查,两种情况也相同。
我不知道我在Angular中有什么错。有想法吗?
答案 0 :(得分:0)
我在Angular代码中发现了错误:
return this.http.post(
'/api/auth/login',
JSON.stringify(credentials),
options // <--- this was missing
)
.pipe( // ...
通过此修改,这是一个可行的解决方案。