Issue
I have trouble connecting my front-end and back-end by using node.js. The result is that the website only represent the HTML code, doesn’t connect with CSS or picture files.
The folder has a structure like this.
root
-src
•picture
○jpg/png file
•css
○css file
•html
○html file
-ws_src
•this file.js
•package.json
const express = require("express");
const path = require("path");
const http = require("http");
const fs = require("fs");
const app = express();
app.use(express.static(path.join(__dirname, '../src/css')));
app.use(express.static(path.join(__dirname, '../src/picture')));
const myQ1Server = http.createServer((req, res) => {
const userPath = req.url;
if (userPath === "/") {
fs.readFile("../src/html/HtmlMainpage.html", function (err, data) {
console.log("Req at: " + userPath);
res.statusCode = 200;
res.setHeader("Content-Type", "text/html;charset=utf-8");
res.write(data);
res.end();
});
}
else if (userPath === "/HtmlAboutuspage.html")
{
fs.readFile("../src/html/HtmlAboutuspage.html", function (err, data) {
console.log("Req at: " + userPath);
res.statusCode = 200;
res.setHeader("Content-Type", "text/html;charset=utf-8");
res.write(data);
res.end();
});
}
else {
console.log("Req at: " + userPath);
res.statusCode = 404;
res.setHeader("Content-Type", "text/plain");
res.write("404 file not found!");
res.end();
}
});
console.log("Listening on the port 3030");
myQ1Server.listen(3030);
Solution
- add all your project files in folder and give him a name for example make it
main
- use the relative url like
./folder/file.css
or../folder/file.css
then add this to your nodejs code
app.use(express.static("/path/main"))