Reputation: 631
Take code like this:
const Post = async (url, body) => {
let res = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
"accept": "*/*"
},
body: JSON.stringify(body)
}).then(r => r.json());
return res;
}
const likePost = async(postId) => {
await Post('https://example.com/api/like', {
_id: postId
})
}
I want to execute the likePost
command in my client side Pug file when the user clicks a like button. I've looked at some Stack Overflow posts and saw that I perhaps had to send a trigger from the server to the client through an HTTP route or something. What do you think would be the idea way to execute a server side command on the client side?
Thanks for any help.
Upvotes: 0
Views: 303
Reputation: 1
The general rendering process of Pug is simple. pug.compile()
will compile the Pug source code into a JavaScript function that takes a data object (called "locals") as an argument. Call that resultant function with your data, and voilà!, it will return a string of HTML rendered with your data.
Upvotes: -1
Reputation: 943142
First, understand what the different parts of the process are.
If you want to do something "when the user clicks a like button" then you are dealing with the HTML and the JavaScript, not with Pug. You might have to edit the Pug file in order to generate the right HTML and JavaScript, but the action isn't happening at the Pug layer.
The JS you've provided might be designed to run in Node.js or client-side. So if you want to run it client-side (when a button is clicked) then you would need to use the addEventListener
method to attach it to the button.
However, your question talks about running a function server-side, so to do that you need to:
.post()
method from Express.js).<form action="/path/to/url" method="POST">
or a link (for GET requests) or Ajax.Upvotes: 2