簡體   English   中英

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

[英]How to resolve 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;

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM