在写cookie是push函数Cannot read property 'push' of undefined

原代码:

app.get("/gonglue",function (req,res) {
    var destination=req.query.desti;
    var mudidiary=req.cookies.mudidi;
    mudidiary.push(destination);

    res.cookie("mudidi",mudidiary)
    res.send(destination+"旅游攻略");
})

 报错
TypeError: Cannot read property 'push' of undefined    at C:\Users\sue\Documents\node\05\04.js:13:15    at Layer.handle [as handle_request] (C:\Users\sue\Documents\node\05\node_modules\express\lib\router\layer.js:95:5)    at next (C:\Users\sue\Documents\node\05\node_modules\express\lib\router\route.js:137:13)    at Route.dispatch (C:\Users\sue\Documents\node\05\node_modules\express\lib\router\route.js:112:3)    at Layer.handle [as handle_request] (C:\Users\sue\Documents\node\05\node_modules\express\lib\router\layer.js:95:5)    at C:\Users\sue\Documents\node\05\node_modules\express\lib\router\index.js:281:22    at Function.process_params (C:\Users\sue\Documents\node\05\node_modules\express\lib\router\index.js:335:12)    at next (C:\Users\sue\Documents\node\05\node_modules\express\lib\router\index.js:275:10)    at cookieParser (C:\Users\sue\Documents\node\05\node_modules\cookie-parser\index.js:71:5)    at Layer.handle [as handle_request] (C:\Users\sue\Documents\node\05\node_modules\express\lib\router\layer.js:95:5)

原因是 var mudidiary=req.cookies.mudidi;在浏览器初次访问时req.cookies.mudidi还为创建,需要给muddiary数组赋值一个[]

修改

app.get("/gonglue",function (req,res) {
    var destination=req.query.desti;
    var mudidiary=req.cookies.mudidi||[];
    mudidiary.push(destination);

    res.cookie("mudidi",mudidiary)
    res.send(destination+"旅游攻略");
})

 

你可能感兴趣的:(nodejs)