'NodeJs: How do I access the functions of my JavaScript backend from my HTML frontend?

Here is my HTML code in index.html.

<!DOCTYPE html>
<html>
    <body>
        <button type="button" onclick="stuff()">Click</button>
        <script>
            async function stuff() {
                await connectToServer();
            }

            async function connectToServer() {
                const xhttp = new XMLHttpRequest(); 
                xhttp.onload = function() { 
                    alert(this.responseText); 
                }; 
                xhttp.open('GET', 'C:/Users/myName/myFolder/index.js', true); 
                xhttp.send();
                return;
            }
        </script>
    </body>
</html>

Then, here is my backend code in index.js.

const express = require('express');
const axios = require('axios');
const port = process.env.PORT || 8080;
const app = express();

app.get('/', (req, res) => {
    res.sendFile('C:/Users/myName/myFolder/views/index.html');

});

app.listen(port, () => console.log(`Listening on port ${port}`));

I can type node index.js on the command line and run this program and go to http://localhost:8080/ . When I do this, the html page shows up as intended. However, when I click the button in order to make a GET request to the server side, I get a console error saying Not allowed to load local resource: file:///C:/Users/myName/myFolder/index.js . I'm using Google Chrome by the way.

I know that it is a security thing, and that you are supposed to make requests to files that are on a web server (they begin with http or https). I suppose then, my question is:

How do I make it so that my server file index.js can be viewed as being on a server so that I can call functions on the backend from my frontend?



Solution 1:[1]

Let's improve your current flow by separating your backend API process from frontend hosting process. While backend can, it's not good in serving static html files (especially for local development purposes).

  1. Run your backend as usual, node index.js. But as soon as this command will become more complicated, you will probably want to use npm scripts and do just npm start)

  2. Run separate server process for frontend. Check out parcel, snowpack, DevServer. It can be as easy as npx parcel index.html, but this command is likely to change frequently with your understanding of your tool features.

  3. To call backend, just add an API endpoint to an express app (just like you already did for serving static content), and call it, using backend process URL.

Usually, you will see your app on http://localhost/ and it should do requests to http://localhost:8080/.

If for some strange reason you will want to dynamically download js file from your server to execute it, you just need to serve this file from your frontend hosting process. In order to do so, different development servers have different techniques, but usually you just specify file extensions and paths you want to be available.

After editing frontend files, you will see hot-reload in browser. You can achieve the same for node process with various tools (start googling from nodemon)

If you find this way of operating not ideal, try to improve it, and check what people already did in this direction. For example, you can run two processes in parallel with concurrently.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1