Home > Enterprise >  node axios as middleware
node axios as middleware

Time:05-01

I am trying to construct a middleware and then use it within the app.get route. I know it's looks very "pioneer" but i am learning.... How can io get it to work?

const BooksMiddle = async (req, res, next) => {
  axios
    .get(`https://www.googleapis.com/books/v1/volumes/? q=${term}&keyes&key=${process.env.GBOOKSKEY}`)
    .then((result) => {
      const data = result.data;
      const books = data.items;
      return books;
 });
   next();
}

module.exports = textMiddle;
app.get("/", textMiddle, (req, res, next) => {
  res.render('index');
});

CodePudding user response:

If the point of this middleware is to get some book data and make that available for your template rendering, then you can put that data into res.locals where templates called from res.render() will automatically look for data:

const bookMiddle = async (req, res, next) => {
    axios
        .get(`https://www.googleapis.com/books/v1/volumes/?q=${term}&keyes&key=${process.env.GBOOKSKEY}`)
        .then((result) => {
            res.locals.books = result.data.items;
            next();
        }).catch(next);
}

module.exports = bookMiddle;

And, then after you import bookMiddle, you can use it like this:

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

If you refer to the books data structure in your template, the template engine will look in res.locals.books for that data (where the middleware puts the data).

  • Related