Home > database >  Jquery on client side with nodejs server
Jquery on client side with nodejs server

Time:12-13

I use nodejs (in a docker-compose container, not sure if that is relevant) to set up a local web app. I would like to use jquery on the client-side to load an HTML file into a div. Unfortunately, it is not working. The initial index.html and the new.html are in the same folder (/frontend/). What am I missing?

Nodejs app:


var app = express();

// home route returns rendered html content
app.get("/", (req, res) => {
  res.sendFile(__dirname   "/frontend/index.html");
});

app.listen(3000, function(){
    console.log('Example app listening on port 3000!');
});

index.html:

<!DOCTYPE html>
<html>
    <head>
        <script src="https://code.jquery.com/jquery-3.6.0.min.js"
            integrity="sha256-/xUj 3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
            crossorigin="anonymous">
        </script>
        
        <script type="text/javascript">
            $(document).ready(function(){
                $("#imported").load("new.html");
            });
        </script>
    </head>
    <body>
        <div> This is content of the index HTML and below is the imported HTML:</div>
        
        <div id="imported"></div>
    </body>
</html>

Lastly the HTML I want to import new.html:

<HTML>
  <head>
  </head>
  <body>
    <p>This is demo text.<p>
  </body>
</html>

CodePudding user response:

Simply use express.static() to serve static HTML files

const app = express();

app.use(express.static("frontend"))

app.listen(3000, function(){
    console.log('Example app listening on port 3000!');
});

If you're just after a plain old static file server, you might find serve simpler...

npx serve frontend

CodePudding user response:

Basically the new.html file is not served.

You need use the following code to serve public files in a directory named public.

var app = express();

// Put new.html into public folder.
// /public/new.html
// /frontend/index.html
app.use(express.static('public'))

// home route returns rendered html content
app.get("/", (req, res) => {
  res.sendFile(__dirname   "/frontend/index.html");
});

app.listen(3000, function(){
    console.log('Example app listening on port 3000!');
});

Ref: https://expressjs.com/en/starter/static-files.html

  • Related