简体   繁体   中英

My HTML cannot show the picture and css that link in other folder (node.js)

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);
  1. add all your project files in folder and give him a name for example make it main
  2. 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"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM