DEV Community

D0xzen
D0xzen

Posted on

Node backend and api calls same project

Hi guys,

I fail to understand how after creating a BackEnd website with Node and Expressjs, if i want to make some functions async ex when someone like a post i want to call an API and return the response in json and append it to the html...

I can create a route and threat it as a API call or i have to create a new project where i use only API calls? it's seems wrong to me cause i want only to allow some functions async...

Top comments (4)

Collapse
 
kryz profile image
Kryz

Hello D0xzen,
you don't need to create a new project.

Add a new api route to your express instance to handle all requests that come from your frontend javascript code, for example:

app.post("/api/posts", (req, res) => {
   // call your service/model or directly db instance
   addPostToDB(req.body)
     .then(newPost => res.json(newPost)
     .catch(err => res.status(500).json({msg: "Cannot add a new post"});
};

or for likes:

app.post("/api/likes/:postId", (req, res) => {
   // call your service/model or directly db instance
   updateLikes(req.params.postId)
     .then(likes => res.json(likes)
     .catch(err => res.status(500).json({msg: "Cannot add a new like"});
};
Collapse
 
d0xzen profile image
D0xzen

Thanks Kryz :D

Yeah at the end i did like that

Collapse
 
scriptmunkee profile image
Ken Simeon

Hi D0xzen,

I'm new in to the NodeJS/Express space, but would like to help. I've figure out most basic dynamics of building an API/Route backend and displaying the data in a web front end within the same code base.

So, for me or others to help we need a bit more context around what you're trying to do. Can you provide a code sample of where you're stuck at? Or can maybe provide some specifics around what you're trying to build?

Cheers!
Ken

Collapse
 
d0xzen profile image
D0xzen • Edited

Hi Ken S Thanks for replying,

I made a backend application with express with all routes i can navigate in my home page where i view all posts that users have posted.

What i want to do right now is to add the like button and upon clicking it making an API call let's suppose /like/:postId and updating the post like numbers with the json response.

The same with comments i want to inside the post detail and get all comment upon clicking the view more button so the same calling /postComment/:postId and getting back all comments and with javascript replacing it inside the DOM without refreshing.

The thing that i found problematic was where i put my API's calls... right now i found an open source project: github.com/dan-divy/spruce where he puts the calls inside the route/api folder

I hope that i'm clear :)