最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - SyntaxError: Unexpected token in Angular - Stack Overflow

programmeradmin0浏览0评论

I want to add my website a user's profile updater. But when I try to open user's profile in my website, I have that error in Angular:

main.ts:6 ERROR SyntaxError: Unexpected token 'e', "eyJhbGciOi"... is not valid JSON
    at JSON.parse (<anonymous>)
    at LocalStorageService.getItem (local-storage.service.ts:17:22)
    at get getDecodedToken [as getDecodedToken] (auth.service.ts:39:42)
    at get getCurrentUserId [as getCurrentUserId] (auth.service.ts:44:29)
    at UserComponent.getUserById (userponent.ts:51:51)
    at UserComponent.ngOnInit (userponent.ts:28:10)
    at callHook (core.mjs:2752:22)
    at callHooks (core.mjs:2721:17)
    at executeInitAndCheckHooks (core.mjs:2672:9)
    at refreshView (core.mjs:12084:21)`

My local-storage.service.ts:

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class LocalStorageService {

  constructor() { }

  setItem(key:string, value:any){
    let json = JSON.stringify(value);
    localStorage.setItem(key, json);
  }

  getItem(key:string){
    let json = localStorage.getItem(key);
    let value = JSON.parse(json);
    return value;
  }

  isSaved(key: string) {
    if (localStorage.getItem(key)) {
      return true;
    }
    return false;
  }

  remove(key: string) {
    localStorage.removeItem(key);
  }

  removeAll() {
    localStorage.clear();
  }
}

auth.service.ts:

`import { HttpClient } from '@angular/mon/http';
import { Injectable } from '@angular/core';
import { LoginModel } from '../models/loginModel';
import { SingleResponseModel } from '../models/singleResponseModel';
import { TokenModel } from '../models/tokenModel';
import { LocalStorageService } from './local-storage.service';
import { UserPasswordModel } from '../models/userPasswordModel';
import { ResponseModel } from '../models/responseModel';
import { JwtHelperService } from '@auth0/angular-jwt';

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  apiUrl="https://localhost:5001/api/auth/";
  public jwtHelperService: JwtHelperService = new JwtHelperService();

  constructor(private httpClient:HttpClient,
    private localStorageService:LocalStorageService) {}

  login(user:LoginModel){
    return this.httpClient.post<SingleResponseModel<TokenModel>>(this.apiUrl+"login", user);
  }

  isAuthenticated(){
    if (localStorage.getItem("token")) {
      return true;
    }else{
      return false;
    }
  }

  updatePassword(userPasswordModel:UserPasswordModel){
    let newUrl = this.apiUrl + "updatepassword";
    return this.httpClient.post<ResponseModel>(newUrl, userPasswordModel)
  }

  get getDecodedToken() {
    let token = this.localStorageService.getItem("token");
    return this.jwtHelperService.decodeToken(token);
  }

  get getCurrentUserId() {
    let decodedToken = this.getDecodedToken;
    let userIdString = Object.keys(decodedToken).filter((t) =>
      t.endsWith('/nameidentifier')
    )[0];
    let userId: number = decodedToken[userIdString];
    return userId;
  }
}

userponent.ts:

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ToastrService } from 'ngx-toastr';
import { User } from 'src/app/models/user';
import { AuthService } from 'src/app/services/auth.service';
import { ProfileService } from 'src/app/services/profile.service';

@Component({
  selector: 'app-user',
  templateUrl: './userponent.html',
  styleUrls: ['./userponent.css']
})
export class UserComponent implements OnInit {

  user:User;
  profileForm:FormGroup;
  passwordForm:FormGroup;
  dataLoaded = false;

  constructor(
    private userService:ProfileService,
    private authService:AuthService,
    private formBuilder:FormBuilder,
    private toastrService:ToastrService
  ) { }

  ngOnInit(): void {
    this.getUserById();
    this.createProfileForm();
    this.createPasswordForm();
  }

  createProfileForm(){
    this.profileForm = this.formBuilder.group({
      id:[Number(this.authService.getCurrentUserId)],
      firstName: ["",Validators.required],
      lastName:["",Validators.required]
    })
  }

  createPasswordForm(){
    this.passwordForm = this.formBuilder.group({
      userId:[Number(this.authService.getCurrentUserId)],
      oldPassword: ["",Validators.required],
      newPassword:["",Validators.required],
      repeatNewPassword:["",Validators.required]
    })
  }

  getUserById(){
    this.userService.getUserById(this.authService.getCurrentUserId)
      .subscribe(response=>{
        this.user = response.data
        this.dataLoaded = true
      });
  }

  updateUserNames(){
    if (this.profileForm.valid) {
      let userModel = Object.assign({}, this.profileForm.value);
      this.userService.updateUserNames(userModel).subscribe(response=>{
        this.toastrService.info(response.message, "Bilgiler Güncellendi.");
        setTimeout(() => {
          window.location.reload();
        }, 1000);
      }, responseError=>{
        console.log(responseError);
        
        this.toastrService.error(responseError.error, "Hata!");
      });
      
    } else {
      this.toastrService.error("Lütfen tüm alanları doldurunuz.", "Hata!");
    }
  }

  updatePassword(){
    if (this.passwordForm.valid) {
      let passwordModel = Object.assign({}, this.passwordForm.value);
      console.log(passwordModel);
      this.authService.updatePassword(passwordModel).subscribe(response=>{
        this.toastrService.info(response.message, "Şifre Güncellendi");
      }, responseError=>{
        this.toastrService.error(responseError.error, "Hata!");
      });
    } else {
      this.toastrService.error("Lütfen tüm alanları doldurunuz.", "Hata!");
    }
  }
}

How can I fix this error? Thanks. I tried lots of thins, but no-one helped me.

I am trying to add a user's profile updater. But this error...

I want to add my website a user's profile updater. But when I try to open user's profile in my website, I have that error in Angular:

main.ts:6 ERROR SyntaxError: Unexpected token 'e', "eyJhbGciOi"... is not valid JSON
    at JSON.parse (<anonymous>)
    at LocalStorageService.getItem (local-storage.service.ts:17:22)
    at get getDecodedToken [as getDecodedToken] (auth.service.ts:39:42)
    at get getCurrentUserId [as getCurrentUserId] (auth.service.ts:44:29)
    at UserComponent.getUserById (user.ponent.ts:51:51)
    at UserComponent.ngOnInit (user.ponent.ts:28:10)
    at callHook (core.mjs:2752:22)
    at callHooks (core.mjs:2721:17)
    at executeInitAndCheckHooks (core.mjs:2672:9)
    at refreshView (core.mjs:12084:21)`

My local-storage.service.ts:

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class LocalStorageService {

  constructor() { }

  setItem(key:string, value:any){
    let json = JSON.stringify(value);
    localStorage.setItem(key, json);
  }

  getItem(key:string){
    let json = localStorage.getItem(key);
    let value = JSON.parse(json);
    return value;
  }

  isSaved(key: string) {
    if (localStorage.getItem(key)) {
      return true;
    }
    return false;
  }

  remove(key: string) {
    localStorage.removeItem(key);
  }

  removeAll() {
    localStorage.clear();
  }
}

auth.service.ts:

`import { HttpClient } from '@angular/mon/http';
import { Injectable } from '@angular/core';
import { LoginModel } from '../models/loginModel';
import { SingleResponseModel } from '../models/singleResponseModel';
import { TokenModel } from '../models/tokenModel';
import { LocalStorageService } from './local-storage.service';
import { UserPasswordModel } from '../models/userPasswordModel';
import { ResponseModel } from '../models/responseModel';
import { JwtHelperService } from '@auth0/angular-jwt';

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  apiUrl="https://localhost:5001/api/auth/";
  public jwtHelperService: JwtHelperService = new JwtHelperService();

  constructor(private httpClient:HttpClient,
    private localStorageService:LocalStorageService) {}

  login(user:LoginModel){
    return this.httpClient.post<SingleResponseModel<TokenModel>>(this.apiUrl+"login", user);
  }

  isAuthenticated(){
    if (localStorage.getItem("token")) {
      return true;
    }else{
      return false;
    }
  }

  updatePassword(userPasswordModel:UserPasswordModel){
    let newUrl = this.apiUrl + "updatepassword";
    return this.httpClient.post<ResponseModel>(newUrl, userPasswordModel)
  }

  get getDecodedToken() {
    let token = this.localStorageService.getItem("token");
    return this.jwtHelperService.decodeToken(token);
  }

  get getCurrentUserId() {
    let decodedToken = this.getDecodedToken;
    let userIdString = Object.keys(decodedToken).filter((t) =>
      t.endsWith('/nameidentifier')
    )[0];
    let userId: number = decodedToken[userIdString];
    return userId;
  }
}

user.ponent.ts:

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ToastrService } from 'ngx-toastr';
import { User } from 'src/app/models/user';
import { AuthService } from 'src/app/services/auth.service';
import { ProfileService } from 'src/app/services/profile.service';

@Component({
  selector: 'app-user',
  templateUrl: './user.ponent.html',
  styleUrls: ['./user.ponent.css']
})
export class UserComponent implements OnInit {

  user:User;
  profileForm:FormGroup;
  passwordForm:FormGroup;
  dataLoaded = false;

  constructor(
    private userService:ProfileService,
    private authService:AuthService,
    private formBuilder:FormBuilder,
    private toastrService:ToastrService
  ) { }

  ngOnInit(): void {
    this.getUserById();
    this.createProfileForm();
    this.createPasswordForm();
  }

  createProfileForm(){
    this.profileForm = this.formBuilder.group({
      id:[Number(this.authService.getCurrentUserId)],
      firstName: ["",Validators.required],
      lastName:["",Validators.required]
    })
  }

  createPasswordForm(){
    this.passwordForm = this.formBuilder.group({
      userId:[Number(this.authService.getCurrentUserId)],
      oldPassword: ["",Validators.required],
      newPassword:["",Validators.required],
      repeatNewPassword:["",Validators.required]
    })
  }

  getUserById(){
    this.userService.getUserById(this.authService.getCurrentUserId)
      .subscribe(response=>{
        this.user = response.data
        this.dataLoaded = true
      });
  }

  updateUserNames(){
    if (this.profileForm.valid) {
      let userModel = Object.assign({}, this.profileForm.value);
      this.userService.updateUserNames(userModel).subscribe(response=>{
        this.toastrService.info(response.message, "Bilgiler Güncellendi.");
        setTimeout(() => {
          window.location.reload();
        }, 1000);
      }, responseError=>{
        console.log(responseError);
        
        this.toastrService.error(responseError.error, "Hata!");
      });
      
    } else {
      this.toastrService.error("Lütfen tüm alanları doldurunuz.", "Hata!");
    }
  }

  updatePassword(){
    if (this.passwordForm.valid) {
      let passwordModel = Object.assign({}, this.passwordForm.value);
      console.log(passwordModel);
      this.authService.updatePassword(passwordModel).subscribe(response=>{
        this.toastrService.info(response.message, "Şifre Güncellendi");
      }, responseError=>{
        this.toastrService.error(responseError.error, "Hata!");
      });
    } else {
      this.toastrService.error("Lütfen tüm alanları doldurunuz.", "Hata!");
    }
  }
}

How can I fix this error? Thanks. I tried lots of thins, but no-one helped me.

I am trying to add a user's profile updater. But this error...

Share Improve this question edited Jan 24, 2023 at 20:41 eglease 2,77411 gold badges20 silver badges34 bronze badges asked Jan 24, 2023 at 20:14 Mert KontMert Kont 431 gold badge1 silver badge4 bronze badges 3
  • Passing json is not valid one. Check in any online json parsers. – Jenish MS Commented Jan 24, 2023 at 20:20
  • 1 FYI: most of your lets should be consts – epascarello Commented Jan 24, 2023 at 20:25
  • 2 so debug what you are getting out of the storage const json = localStorage.getItem(key); console.log({key, json}); and figure out why it would be throwing an error. – epascarello Commented Jan 24, 2023 at 20:26
Add a ment  | 

1 Answer 1

Reset to default 3

As the error says; Unexpected token 'e', "eyJhbGciOi"... is not valid JSON. You are trying to parse a plain string represents token itself, not a valid string represents a json object.. Therefore it fails when trying to parse it.

Either update the code where you directly store your token as string on your local storage or just use localStorage.getItem('token') without parsing.

发布评论

评论列表(0)

  1. 暂无评论