Problem loading all of the resources for a single page application from REST API using Node.js and Express.js

30 Views Asked by At

I'm trying to run this Single Page Application in node.js + express.js but I can only load the html file and not the required 2 JavaScript files. Project Structure

weather.js

const { Router } = require("express");
const controller = require("./controller");
const path = require("path");

const router = new Router();

router.get("/home", (req, res) => {
  res.sendFile(path.join(__dirname, "public", "home.html"));
});

router.post(
  "/district/",
  [controller.auther, controller.admin],
  controller.addDistrict
);
router.post(
  "/data/",
  [controller.auther, controller.editor],
  controller.addData
);
router.get("/", [controller.auther, controller.viewer], controller.getData);
router.post("/auth", controller.auth);

module.exports = router;

server.js

const express = require("express");
const weatherRoutes = require("./src/weather");
const path = require("path");

const app = express();
const port = 3000;

app.use(express.json());

app.use(express.static(path.join(__dirname, "public")));

app.use("/api/weather", weatherRoutes);

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

home.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Hello World</title>
  </head>
  <body>
    <div id="map"></div>
    <script type="text/javascript" src="countrymap.js"></script>
    <script type="text/javascript" src="mapdata.js"></script>
  </body>
</html>

Error

Tried change the file locations of the js files.

2

There are 2 best solutions below

5
traynor On

Try adding base tag to home.html

  <base href="/" target="_blank">

The <base> HTML element specifies the base URL to use for all relative URLs in a document. There can be only one <base> element in a document.

<!DOCTYPE html>
<html lang="en">
  <head>

    <base href="/" target="_blank">
    
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Hello World</title>
  </head>
  <body>
    <div id="map"></div>
    <script type="text/javascript" src="countrymap.js"></script>
    <script type="text/javascript" src="mapdata.js"></script>
  </body>
</html>
0
Nevanjith De Silva On
  • Moved public folder out of src
  • Removed all code relevant to hosting a SPA
  • Added this code to server.js app.use(express.static("public"));
  • Changed home.html to index.html
  • Works at http://localhost:3000/