AngularJS unexpected token in fromJson()


The following line of code:

var sid = $cookieStore.get('PHPSESSID');

is throwing this error:

SyntaxError: Unexpected token m
at Object.parse (native)
at Object.fromJson (
at Object.angular.module.factory.factory.get (
at Object.getAllImages (
at new Management (
at invoke (
at Object.instantiate (
at $get (
at update (
at Object.$get.Scope.$broadcast ( 

So, I put a breakpoint at angular.js at line 779. The code there is:

777    function fromJson(json) {
778        return isString(json)
779            ? JSON.parse(json)
780            : json;
781    }

The value of json as passed into JSON.parse() is "mnp801fap6kor50trgv4cgk7m2".

I also noticed that other things getting passed into that method usually have two quotes around them, like ""userName"" for example.

Please help. I'm banging my head against this for a couple hours.

Or, if someone knows a better way to get the php session id out of the cookies using Angular, that would be great, too. (Yes, I could do it using jQuery or bare-metal JS, but I'd prefer to keep using Angular).

Thanks in advance!!!

Problem courtesy of: cutmancometh


It doesn't appear that $cookieStore is meant to read cookies that weren't created by $cookieStore. From the comments:

* @description
* Provides a key-value (string-object) storage, that is backed by session cookies.
* Objects put or retrieved from this storage are automatically serialized or
* deserialized by angular's toJson/fromJson.

The automatically serialized or deserialized is the important part. I was able to reproduce your problem here:

You probably want to use $cookies instead, like so:

angular.module('myApp', ['ngCookies']);
function CookieCtrl($scope, $cookies) {
    console.log('haha', $cookies.PHPSESSID);
Solution courtesy of: Langdon


Or you can simply wrap the $cookieStorage in a function and return a value or an empty string.

var sid = getPHPSESSID();

function getPHPSESSID() {
   return $cookieStore.get('PHPSESSID') || '';

In that case you'll use the angular service with it's pros and if you don't put the key-value pair in cookies, you'll get the empty string in result

Discussion courtesy of: Julia Usanova

This recipe can be found in it's original form on Stack Over Flow.