It is so ridiculous but i'm stuck for days in a very meaningless code situation.
I can't have the css, the image to load on my nodejs server.
I tried many things (express.static, etc.) but nothing seems to work.
Can you help me ?
app.js
const express = require('express')
const app = express()
const port = 3000
app.listen(port, () => {
console.log(`app running on port ${port}`)
})
app.use((req, res, next) => {
res.sendFile(__dirname "/index.html");
})
Index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Découvrez ma newsletter pour acquérir les bases du marketing digital et du growth. Zennit est une agence Growth spécialisée en scraping et génération de leads.">
<title>Agence Growth - spécialité scraping et leads generation</title>
<link rel="icon" type="image/png" href="assets/images/favicon.png" />
<link rel="stylesheet" href="./assets/css/web_version.css">
<link rel="stylesheet" href="./assets/css/mobile_version.css">
<link rel="stylesheet" href="./assets/css/tablet_version.css">
</head>
File structure
Thank you for your help :)
CodePudding user response:
To statically server your assets
directory as /assets
, you'll want something like this
app.use("/assets", express.static(__dirname "/assets");
This means any request to /assets/*
will serve static files from your assets
directory, eg
<link rel="stylesheet" href="/assets/css/web_version.css" />
<img src="/assets/images/some-image.png" />
<script src="/assets/js/some-frontend-script.js"></script>
You're also serving index.html
for every single request. Change it to the following to only serve it for GET /
or GET /index.html
app.get(["/", "/index.html"], (req, res) => {
res.sendFile(__dirname "/index.html");
})
I'd recommend keeping all static files, including index.html
in one directory to serve statically. For example, with this directory structure
app/
├─ public/
│ ├─ assets/
│ │ ├─ css/
│ │ ├─ js/
│ │ ├─ images/
│ ├─ index.html
├─ app.js
├─ package.json
All you'd need is
app.use(express.static("public"))
There would be no need for res.sendFile()
at all.