Home > other >  NodeJs: How do I access the functions of my javascript backend from my HTML frontend?
NodeJs: How do I access the functions of my javascript backend from my HTML frontend?

Time:05-25

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?

CodePudding user response:

You have to make an HTTP request to a URL provided by the server.

The only URL your server provides is http://localhost:8080/ (because you are running an HTTP server on localhost, have configured it to run on port 8080, and have app.get('/', ...) providing the only path.

If you want to support other URLs, then register them in a similar way and write a route to handle them.

The express documentation will probably be useful.

You should not need to load your server-side code into the browser. It's server-side code. It runs on the server. It isn't client-side code. It doesn't run in the browser. The browser does not need access to it.

If you want to load some actual client-side JS from the server, then use <script src="url/to/js"></script> (and not Ajax) and configure express' static middleware.

CodePudding user response:

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.

  • Related