whoAmi21
whoAmi21

Reputation: 105

express, creating cookie with json

i'm using express 3.x and trying to create a cookie.

i'm trying following json:

res.cookie('cart', {
                styles: styles[product],
                count: 0,
                total: 0
            }) 

where product is:

{product: {
       "_id": style._id,
       "style": style.style,
       "a": style.a,
       "color": color,
       "price": style.price,
       "desc": style.desc,
       "img": style.img,
       "category": style.category,
       "quantity": 1
        }

}

and

var product = req.params.a + "_" + style.id;

i can't make 'styles[product]' to work. what's my problem??

i need to create a json that looks like 'req.cookies.cart.styles[product]' this

please help!

Upvotes: 0

Views: 6346

Answers (3)

Gesugao-san
Gesugao-san

Reputation: 75

Cookies are usually transmitted in this format:

"var1=value1;var2=value2;"

instead of

{"var1": "value1"; "var2": "value2"}

I had a similar problem - I needed to convert a JSON object to a cookie, and I was able to solve it by converting this object to a string, and then replacing some key syntax elements:

var req_options = {
    headers: {
        // ...
        'Cookie': JSON.stringify(
            {"var1": "value", "var2": "value2"}
            ).replace(":", "=").replace(/\{|\}|\"/g, "").replace(",", ";")
    }
};

In my case, the full version of the working code looks something like this:

const request = require('request');

var req_options = {
    uri: '...',
    headers: {
        //'Accept': 'text/html', 'Accept-Charset': 'utf-8', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)',
        'Cookie': JSON.stringify(
            {"var1": "value", "var2": "value2"}
            ).replace(":", "=").replace(/\{|\}|\"/g, "").replace(",", ";")
    }
};

function doRequest() {
    return new Promise((resolve, reject) => {
        process.stdout.write("Calling for " + req_options.uri + "... ");
        request(req_options, function (error, res, body) {
            if (res.statusCode === 200) {
                console.log("200 OK, answer:\n", JSON.parse(body)); //resolve("200 OK");
            }
            if (error)
                return reject(error);
        });
    });
}

async function mainLoop() {
    console.clear();
    console.log("Hi");
    console.log("headers.cookie: \"" + req_options.headers.Cookie + "\"");
    await doRequest().then(function(val) {
        console.log(val);
    }).catch(function(err) {
        console.error(err);
    });
    console.log("Bye");
}

mainLoop();

In your case, it might look something like this:

res.cookie('cart',
    JSON.stringify({
        styles: styles[product],
        count: 0,
        total: 0
    }).replace(":", "=").replace(/\{|\}|\"/g, "").replace(",", ";")

Upvotes: 1

HILARUDEEN S ALLAUDEEN
HILARUDEEN S ALLAUDEEN

Reputation: 1752

You can only store a string value in cookie. Let's take a situation that you want to store a boolean true in a cookie, It is converted into a string "true" and stored in browser cookie. Following code will do the same

res.cookie('myBoolean', true)

Now boolean true stored as string "true" in cookie.

In your case you trying to store an object in cookie. So internally your object converted into string by calling function like follows

var myObj = {name: 'myObj'}
myObj.toString()

Exactly In your code, the cookie consist value

res.cookie('cart', ({
                styles: styles[product],
                count: 0,
                total: 0
            }).toString())

You can check browser and you can see the cookie as follows

cart:[object Object]

So the better idea is, You have to use JSON.stringify/JSON.parse as follows

Set Cookie:

res.cookie('cart', JSON.stringify({ styles : styles[product], count : 0, total : 0 }))

Get Cookie

var cookieData = JSON.parse(req.cookies.cart)

Note: However you can store cookie by using JSON.stringify, store such a cart information is not advisable. You have to prefer session storage instead of cookie.

Upvotes: 4

Alex Netkachov
Alex Netkachov

Reputation: 13522

It is very unclear what you want to achieve. If product is really the object then it hardly can be used as a key - it will be converted to the [object Object] string and styles[product] will be equal to styles['[object Object]'].

If styles[product] returns the product like one that is in the second code block, then style.id probably should be style.product._id.

The best I can suggest is to check all the intermediate steps by adding console.log. For example:

console.log('keys of styles:', Object.keys(styles));
console.log('product:', product);
res.cookie('cart', {
    styles: styles[product],
    count: 0,
    total: 0
})

This will show you what exactly is added to the cookie. Use the similar approach to test other parts of the algorithm.

Upvotes: 0

Related Questions