简体   繁体   中英

how do I send data from one app.js file to index.ejs file in Routes

error is that my blogs variable which i am passing as an object that contain data to index page is not defined. code for indexpage:

Thanks in advance.

//INDEX ROUTE
app.get("/blogs", function (req, res){
    Blog.find({}, function (err, blogs) {
        if (err) {
            console.log("ERROR!");
        } else {
            res.render("index", {blogs: blogs});
        }
    });
});

if you're using mongoose, find method return promise,so make function async and use await before using find :

app.get("/blogs", function async (req, res){
  let blogs = await Blogs.find({});
  res.render("index", {blogs});
});


or
using .then to get data from find method:

app.get("/blogs", function (req, res){
  Blog.find({}).then(blogs=>{
     res.render("index", {blogs}); //if key and value are the same you can skip passing key
  }).catch(err=>{
     console.log(err)
  });
});

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