如何解决 SyntaxError: Unexpected token M in JSON at position 0?

时间:2021-07-13 15:45:45

标签: javascript json syntax-error jsonparser unexpected-token

在尝试获取针对本地存储中的“auth”密钥存储的授权信息时,我收到 SyntaxError: Unexpected token M in JSON at position 0

附加信息:针对“auth”键存储的值基本上是键值对的对象。

代码如下:

public async getAuthInfo(): Promise<{ accessToken: string }> {
const authInfo = <string>(<any>browser.executeScript("return localStorage.getItem('auth');"));
if (!authInfo) {
  throw { error: 'No authorization details found in local storage.' };
}
try {
  return JSON.parse(authInfo);
} catch (error) {
  console.log("Error: " + error);
}
}

const authInfo = await this.getAuthInfo();
this.httpService.headers['Authorization'] = `Bearer ${authInfo.accessToken}`;

authInfo 值看起来像这样

"{\"accessToken\":\"yuiooy\",\"authenticated\":true,\"sessionAcquired\":true}"

请帮我解决这个问题。

1 个答案:

答案 0 :(得分:0)

我试过了,对我有用

public async getAuthInfo(): Promise<{ accessToken: string }> {
const authInfo = <any>browser.executeScript("return JSON.parse(localStorage.getItem('auth'));");
if (!authInfo) { throw {error : 'No authorization details found in local storage.'};}
return authInfo;

}