abdelrahmannasser
abdelrahmannasser

Reputation: 31

Rendering HTML file with res.sendFile() in Express.js

I'm trying to render my HTML file with some a local CSS file, local JS file and two remote files as links

but all I got is a plain HTML in the browser

here is the top of my HTML file (index.html):

<script src="src/drawflow.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="src/index.css" />
<link
  rel="stylesheet"
  href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"
/>

This is my server code (app.js):

"use strict";
const express = require("express");
const path = require("path");

const app = express();

app.use(express.static(__dirname + "/src"));

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

app.listen(process.env.port || 4000, () => {
  console.log("listening to port 4000...");
});

and here is my file structure: file structure

The index.html file is working just fine when opened in the browser but it can't be fetched properly from the server.

Any ideas ?

Upvotes: 1

Views: 2308

Answers (2)

abdelrahmannasser
abdelrahmannasser

Reputation: 31

Thanks to the comment by Chris Short

I replaced

app.use(express.static(__dirname + "/src"));

to

app.use('/src', express.static(path.join(__dirname + '/src')));

and it worked perfectly.

Thanks a lot.

Upvotes: 1

Chris
Chris

Reputation: 1584

If I'm understanding correctly. The assets for your HTML file are not being fetched properly, so your HTML is showing as bare when you access through the browser. With this understanding, the reason your assets are not loading properly is due to the way your app.js is set up.

Currently you are trying to access href="src/index.css" in your header, however all of your assets are going to be found from your website root. Expressjs handles all app.use statements as middleware and by default are attached to the root of your website. If you would like to have this accessible from "src" then you will need to set up your express.static a bit differently like so.

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

See the below for more info

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

https://expressjs.com/en/guide/using-middleware.html

Upvotes: 0

Related Questions