简体   繁体   中英

convert vanilla JS to work with Nodejs, Mongo, and Express

I am working on a blog project for a class using Nodejs, Mongo, and Express. We have been building up to using Express. I had previous JS code to create a slideshow for blog posts. I now need the slideshow to access data from MongoDB and route to a post.ejs file with the matching title (so it can find it on the database and show it on the post.ejs file). I cannot use the slideshow buttons because as I mentioned before that was vanilla js used before being introduced to Node. How can I convert the old vanilla JS to work with express and pull data from Mongo DB? I have managed to learn a lot on my own but I'm stuck now.

Here it my GitHub repository.https://github.com/mmercad4/Marco_800951815/tree/milestone-5

The old JS is in /public/assets/main.js

My post controller is in controllers/postController.js

My jquery folder for ajax is in public/assets/jquery.js

And finally my index.ejs and post.ejs are located in the views folder.

You can modify your vanilla JS files and make them into ejs templates. Use the same syntax that you used for post.ejs so that you can access the data you pass in.

On your server you should set up a route handler such as app.get("/example") . Inside of your route handler, you should query your mongodb instance for the data you need. Now take your newly modified ejs file and render it, passing in the result of the query from mongodb. Here's an example:

app.get("/example", (req, res) => {
    const data = getDataFromMongo() // insert your query here
    res.render("main", data);
}

If you want your client to be responsible for fetching the data instead, then skip transforming your vanilla files into ejs, and you can simply return the mongodb data as JSON like so:

app.get("/example", (req, res) => {
    const data = getDataFromMongo() // insert your query here
    res.json(data);
}

Now in your client side code, make an ajax GET request to "/example" and you can use the JSON returned however you wish. No need for ejs template syntax here.

So it's up to you to how you want to control access to your data. The first method handles everything server-side. The second method splits responsibility between server and client. In this case, the server acts as more of a data API than a rendering engine.

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