Search code examples
javascriptnode.jsfetchsingle-page-application

Send a response from the serve-side to client-side (Node.js, javascript)


Based on the following structure below, I want to send my response (simple array ["Tom", "Bob", "Sam"]) from the server.js to index.js Is it possible?

server.js

app.get("/*", (req, res) => {
    res.sendFile(path.resolve(__dirname, "frontend", "index.html"));
});

app.post('/settings', function(req, res, next){
res.status(200).json({
                ok: true,
                data: ["Tom", "Bob", "Sam"]
            }); 
});

app.listen(process.env.PORT || 3000);

frontend/index.html

    <nav class="nav">
        <a href="/">Dashboard</a>
        <a href="/settings">Settings</a>
    </nav>
    <div id="app"></div>
    <script type="module" src="/static/js/index.js"></script>

/frontend/static/js/index.js

document.querySelector("#app").innerHTML = await view.getHtml(); // load page.html
//console.log(data);

/frontend/static/html/page.html

        <button id="btn">Save</button>
       <script>
     
   var btn = document.getElementById("btn");
btn.addEventListener("click", function() {

  fetch('/settings', {
    method: 'POST', 
           headers: {
            "Content-Type": "text/plain"
        },
    body: JSON.stringify(anotherData), 
    headers: {
      'Content-Type': 'application/json'
    }
  }).then(response => response.json())
    .then(function(response) {
        if (response.ok) {
            console.log('got data: ', response.data);
        }
    }).catch(function(error) {
        console.log(error);
    });
  

}, false);
   </script>

Solution

  • Thank you for the comment - I believe I understand what you're asking for now.

    If you want to retrieve the data in your index.js file, the best way to handle this is probably to move your request code to index.js. Remove the tag from your page.html file and instead put it in index.js. The code in index.js will run once the page loads, similarly to what is happening in the page script.

    You'll need to wait until your fetch completes before doing anything with the resulting data, but if you move the fetch into your index.js you can call other functions in the file with the data, or alternatively declare a variable outside of your fetch call to let other functions in your index.js use it.