我的应用程序使用,node.js,expressJS,jQuery。使用jQuery cookie插件,我从客户端创建了一个cookie,然后可以成功读取它。我想从服务器端读取该cookie(node.js,表达js),但不能。
var products_cart=new Array();
for(var i =1; i<5; i++){
var prod_cart_indiv= new Object();
prod_cart_indiv.prod_id=i;
prod_cart_indiv.price=(200+i);
prod_cart_indiv.num_total=(4+i);
prod_cart_indiv.name='printing products _ '+i;
prod_cart_indiv.img='a_'+i+'.jpg';
products_cart.push(prod_cart_indiv);
}// end of for loop
$.cookie('products_cart',JSON.stringify(products_cart));
var products_cart_found =JSON.parse($.cookie('products_cart'));
if(window.console){
console.log("Logging products_cart_found ");
console.dir(products_cart_found);
}
服务器端node.js代码:
var util = require('util');
app.get('*',function(req,res){
var get_cookies = function(request) {
var cookies = {};
request.headers && request.headers.cookie.split(';').forEach(function(cookie) {
var parts = cookie.match(/(.*?)=(.*)$/)
cookies[ parts[1].trim() ] = (parts[2] || '').trim();
});
return cookies;
};
var products_cart_found= get_cookies(req)['products_cart'];
console.log(util.inspect(products_cart_found, false, null));
});
我在命令提示符中找到的是:
'%5B%7B%22prod_id%22%3A1%2C%22price%22%3A201%2C%22num_total%22%3A5%2C%22name%22%
3A%22printing%20products%20_%201%22%2C%22img%22%3A%22a_1.jpg%22%7D%2C%7B%22prod_
id%22%3A2%2C%22price%22%3A202%2C%22num_total%22%3A6%2C%22name%22%3A%22printing%2
0products%20_%202%22%2C%22img%22%3A%22a_2.jpg%22%7D%2C%7B%22prod_id%22%3A3%2C%22
price%22%3A203%2C%22num_total%22%3A7%2C%22name%22%3A%22printing%20products%20_%2
03%22%2C%22img%22%3A%22a_3.jpg%22%7D%2C%7B%22prod_id%22%3A4%2C%22price%22%3A204%
2C%22num_total%22%3A8%2C%22name%22%3A%22printing%20products%20_%204%22%2C%22img%
22%3A%22a_4.jpg%22%7D%5D'
然而在浏览器控制台中,我得到了下面的输出(手工制作以呈现):
Array[4]
Object: img: "a_1.jpg"name: "printing products _ 1"num_total: 5price: 201prod_id: 1
Object: img: "a_2.jpg"name: "printing products _ 2"num_total: 6price: 202prod_id: 2
Object: Objectimg: "a_3.jpg"name: "printing products _ 3"num_total: 7price: 203prod_id: 3
Object: Objectimg: "a_4.jpg"name: "printing products _ 4"num_total: 8price: 204prod_id: 4
如何在变量中获取cookie值,以便我可以迭代它,就好像它是一个对象数组&gt;