鍍金池/ 問(wèn)答/HTML5  HTML/ node獲取cookie失敗

node獲取cookie失敗

最近在學(xué)習(xí)nodejs 并打算寫一個(gè)個(gè)人博客

我在獲取cooike時(shí)報(bào)錯(cuò)
clipboard.png

流程
1.當(dāng)?shù)顷懗晒r(shí)設(shè)置cookie





>   res.cookie('userInfo',{ _id: doc._id,username:doc.username},{domain:'localhost',maxAge:100000,httpOnly:true,});//httpOnly 只有服務(wù)器可以修改

2然后跳轉(zhuǎn)到首頁(yè)路由中 獲取用戶cookie

router.get('/', function (req, res, next) {
    if(req.cookies["userInfo"]._id!==null){
        data_home.user_info.user_id=req.cookies["userInfo"]._id;
        data_home.user_info.user_name=req.cookies["userInfo"].username;
    }
    res.render('index', data_home);

    // res.json(docs);
});

這樣是可以成功讀取cookie的

但是如果我沒(méi)有登陸的話直接獲取req.cookies["userInfo"]._id就回提示TypeError: Cannot read property '_id' of undefined(error路由觸發(fā)); 所以我在首頁(yè)的路由也加了判斷 然后我發(fā)現(xiàn)不管怎樣只要獲取不到cookie就會(huì)出錯(cuò)

怎么才能正確判斷cookie是否存在?

我用的是express后臺(tái)框架

回答
編輯回答
維他命

舉個(gè)例子

var a={};
a.v//是不是undefined
a.v.c//你覺(jué)的它能不報(bào)錯(cuò)嗎Cannot read property 'c' of undefined

你的判斷要加上
req.cookies["userInfo"]是否存在

2017年12月11日 09:27