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

问题描述

在尝试获取针对本地存储中的“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}"

请帮我解决这个问题。

解决方法

我试过了,对我有用

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;

}