Home > other >  Is it possible to automatically send render data each request?
Is it possible to automatically send render data each request?

Time:10-12

I want to send data from my config.js file to every single render. Is there a way to do this with a few lines of code instead of having to manually push the data with every single render function?

Here's what I mean

const data = require("config.js").coolData;

app.get("/", (req, res) => {
  res.render("index", {data});
});

app.get("/request2", (req, res) => {
  res.render("index", {data);
});

app.get("/request3", (req, res) => {
  res.render("index", {foo, data);
});

Is there a way to easily send data to all three?

CodePudding user response:

If you are using express, you can do it with res.locals; in a middleware For example:

const data = require("config.js").coolData;
app.use((req, res, next) => {
    res.locals.data = data;
    next();
});
...

Just be sure to place the middleware above before any other route

  • Related