无法读取Cookie中未定义的属性“程序”?

时间:2018-08-03 17:21:03

标签: node.js express cookies

我是Nodejs程序的初学者,我尝试做简单的cookie程序。我成功设置和删除了cookie。但是我无法获得以前设置的cookie。它显示错误。有人可以告诉我如何获取nodejs中的cookie预先感谢。...

const express=require("express");
const cookieParser=require("cookie-parser");
const app=express();
const router=express.Router();
const port=process.env.Port||8086;
app.use(router);
app.use(cookieParser());
router.get("/setcookie",function(req,res)
{
    console.log("Come in to set the cookie");
    res.cookie("program","NodeJS"/*,{maxAge:60000}*/);
    res.cookie("Database","MongoDB"/*,{maxAge:1200000}*/);
    console.log("Cookie set successfully");
    res.send("Cookie set successfully");
});
router.get("/deletecookie",function(req,res)
{
    console.log("come in to delete the cookie");
    res.clearCookie("program");
    res.send("Cookie deleted successsfully");
});
router.get("/getcookie",function(req,res)
{
    console.log("Come in to read the cookie");
    console.log(req.cookies['program']);
    console.log(req.cookies['Database']);
    res.send("Cookie Accessed successfully");
});
app.listen(port,function()
{
    console.log("server is listening on port 8086");
});


ERROR I GOT:

TypeError: Cannot read property 'program' of undefined
    at C:\Users\VIGNESH\WebstormProjects\cookies-middleware\simple-cookies.js:25:28
    at Layer.handle [as handle_request] (C:\Users\VIGNESH\WebstormProjects\cookies-middleware\node_modules\express\lib\router\layer.js:95:5)
    at next (C:\Users\VIGNESH\WebstormProjects\cookies-middleware\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (C:\Users\VIGNESH\WebstormProjects\cookies-middleware\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (C:\Users\VIGNESH\WebstormProjects\cookies-middleware\node_modules\express\lib\router\layer.js:95:5)
    at C:\Users\VIGNESH\WebstormProjects\cookies-middleware\node_modules\express\lib\router\index.js:281:22
    at Function.process_params (C:\Users\VIGNESH\WebstormProjects\cookies-middleware\node_modules\express\lib\router\index.js:335:12)
    at next (C:\Users\VIGNESH\WebstormProjects\cookies-middleware\node_modules\express\lib\router\index.js:275:10)
    at Function.handle (C:\Users\VIGNESH\WebstormProjects\cookies-middleware\node_modules\express\lib\router\index.js:174:3)
    at router (C:\Users\VIGNESH\WebstormProjects\cookies-middleware\node_modules\express\lib\router\index.js:47:12)

1 个答案:

答案 0 :(得分:1)

您需要在cookieParser()之前添加router,因此代码将是

app.use(cookieParser());
app.use(router);

因为否则控件甚至无法进入cookieParser