简体   繁体   中英

express.js public folder not being recognised

I have developed a simple server in Node.js using Express and I have set the public folder to serve static files.

In my root index.js , I have the following code:

const express = require('express');
const app = express();
const http = require('http').Server(app);
const fs = require('fs');

app.use(express.static(__dirname + '/public'));

app.get('/', (req, res) =>  {
    res.sendFile(__dirname + '/public/index.html'); 
});

http.listen(3000, () => console.log('started server on *:3000'));

And the directory structure is:

root 
|---index.js
|---package.json
|---public
|   |---index.html
|   |---cs
|   |   |---index.css
|   |---js
|   |   |---index.js

In the index.html in the public folder, I have the following code:

<head>
    <script src="js/index.js"></script>
    <link rel="stylesheet" src="css/index.css" type="text/css" >
</head>

But no CSS is being rendered. How can I resolve this?

Try changing this:

app.use(express.static(__dirname + '/public'));

To this:

app.use(express.static('public'));

Replace src attribute in link tag to href . If this doesn't work then try below solution.

I'm considering your server is running on http://localhost:3000/

So update the url in src of your index.html in public folder by appending with the base url as I did below.

<head>
    <script src="http://localhost:3000/js/index.js"></script>
    <link rel="stylesheet" href="http://localhost:3000/css/index.css" type="text/css" >
</head>

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