在我的应用程序中,我尝试添加JWT安全性。在响应文本中,我添加了用户和用户名的权限。全部工作,但如果我尝试拆分响应文本,它不起作用。
login(username: string, password: string): Observable<boolean> {
return this.http.post(AUTH_USER_PATH, JSON.stringify({username: username, password: password}),
this.getPlainRequestOptions())
.map((response: Response) => {
let token: string = response.headers.get('Authorization').slice(7); //working
let authorities: string[] = JSON.parse(response.text().split('|')[0]); //not working
let username: string = JSON.parse(response.text().split('|')[1]); //not working
console.log(authorities);
console.log(username);
if (token) {
localStorage.setItem('token', JSON.stringify(token));
localStorage.setItem('authorities', response.text());
localStorage.setItem('username', response.text());
return true;
} else {
return false;
}
})
.catch((error: any) => Observable.throw(error));
}
如果我不使用拆分,那么在控制台中我看到:
[ROLE_USER, ROLE_ADMIN]|user1
如何轻松拆分此字符串(数组)以获得此结果?
authorities = [ROLE_USER, ROLE_ADMIN];
username = "user1";
答案 0 :(得分:0)
|在正则表达式中,字符是一个特殊字符。 尝试使用\
转义特殊字符let authorities:string [] = JSON.parse(response.text()。split(&#39; \ |&#39;)[0]);
这是一个应该有用的链接What special characters must be escaped in regular expressions?