在线等啊、各位大神。express 4中ejs表单csrf的值为undefined,求大神给提示
发布于 7个月前 作者 heixiaoshan 700 次浏览
包
{
  "name": "biizhi",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node ./bin/www"
  },
  "dependencies": {
    "express": "~4.2.0",
    "static-favicon": "~1.0.0",
    "morgan": "~1.0.0",
    "cookie-parser": "~1.0.1",
    "body-parser": "~1.0.0",
    "connect-mongo": "^0.4.0",
    "mongoose": "~2.8.0",
    "debug": "~0.7.4",
    "cheerio":"*",
    "request": "*",
    "ejs": "~0.8.5",
    "express-session": "~1.6.3",
    "validator":"~3.16.0",
    "xss":"~0.1.9",
    "csurf":"~1.3.0"
  }
}
以下为APP.JS
app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(session({
    resave:true,
    saveUninitialized:true,
    key: 'sid',
    secret: settings.cookieSecret,
    store: new MongoStore({
        db: settings.db
    })
}));
app.use(csrf());
app.use(function(req, res, next){
    res.locals.csrf = req.session ? req.session._csrf : "";
    next();
});
app.use(express.static(path.join(__dirname, 'public')));

ejs表单中
<form>
     <input type='hidden' name='_csrf' value='<%= csrf %>' />
</form>

报错:
invalid csrf token

403

Error: invalid csrf token
    at createToken (D:\Workspaces\HTML5\biizhi\node_modules\csurf\index.js:107:19)
    at Layer.handle (D:\Workspaces\HTML5\biizhi\node_modules\csurf\index.js:67:24)
    at trim_prefix (D:\Workspaces\HTML5\biizhi\node_modules\express\lib\router\index.js:240:15)
    at D:\Workspaces\HTML5\biizhi\node_modules\express\lib\router\index.js:208:9
    at Function.proto.process_params (D:\Workspaces\HTML5\biizhi\node_modules\express\lib\router\index.js:269:12)
    at next (D:\Workspaces\HTML5\biizhi\node_modules\express\lib\router\index.js:199:19)
    at D:\Workspaces\HTML5\biizhi\node_modules\express-session\index.js:285:9
    at D:\Workspaces\HTML5\biizhi\node_modules\connect-mongo\lib\connect-mongo.js:222:17
    at D:\Workspaces\HTML5\biizhi\node_modules\connect-mongo\node_modules\mongodb\lib\mongodb\collection\query.js:147:5
    at Cursor.nextObject (D:\Workspaces\HTML5\biizhi\node_modules\connect-mongo\node_modules\mongodb\lib\mongodb\cursor.js:733:5)

控制台结果:
_csrf:undefined

求大神给个提示啊

7 回复

res.locals.token = req.csrfToken();

app.use(function(req, res, next){ res.locals.csrf = req.session ? req.session._csrf : ""; res.locals.token = req.csrfToken();//加在这里吗? next(); });

结果还是一样,前台标签中_csrf 的值还是 undefined

app.use(function(req, res, next){ console.log(req.session);//查下中间件位置。我刚没看中间件。 res.locals.csrf = req.session ? req.session._csrf : ""; next(); });

你上面的代码赋值的 local 变量是 token,但你要取 _csrf… 要不你去看看我们 cnode 是怎么解决这个问题的?

@alsotang 多谢。有在研究Cnode代码。

回到顶部