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.
CodePudding user response:
First, understand what the different parts of the process are.
- The browser makes an HTTP request to the server
- The server runs a function registered against a particular URL
- That functions passes some data to the pug library and gets some HTML back then it sends that HTML to the browser
- The browser renders the HTML and runs any JavaScript in it
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:
- Configure your server to run the function when a request is made to a given URL. How you do that depends on how you have built your server (e.g. by using the
.post()
method from Express.js). - Make a request to that URL when the button is clicked. Typically you would do this with
<form action="/path/to/url" method="POST">
or a link (for GET requests) or Ajax.
CodePudding user response:
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.