简体   繁体   中英

Nodejs how response locals on each get view on app.use

I am trying to handle simple user information through cookies, this information is visible in my layout through res.render, but I saw it very tedious, since it will always be simple information and I would have to be doing it in each .get (), then in app.js I did this:

app.js

app.use(function(req,res, next){
  var cookies = req.cookies;
  if(!cookies.UserData){
    console.log('cookies no exists');
  }
  else{
    console.log('cookies');
    res.locals.user = cookies.UserData;
    next();
  }

});
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

layout.ejs

<%- user.username %>

but "user" was not defined, but in my error.ejs When a 404 was generated, I put "<%- user.username %>" it in and it worked.

but it only works on 404 catches and not in general, what am I doing wrong? how I do this?

how I solved it

In my Router-level middleware:

var express = require('express');
var router = express.Router();


router.use(function(req,res, next){
  var cookies = req.cookies;
  if(!cookies.UserData){
    console.log('cookies no exist');
  }
  else{
    console.log('cookies');
    res.locals.user = cookies.UserData;
    next();
  }
});

I put it first in the router-level middleware, above all the other http methods

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM