简体   繁体   中英

node.js - Static files CSS / JS not working in express

I Understand many people have asked the same question but i just can't get this to work for me at all.

I am trying to make a socket.IO application and are following the tutorials but just can't get CSS and JS to be loaded to the page. The application just always sends the html page.

My folder structure.

./server.js
./public
    /css
        /styles.css
    /js
        /client.js
    /index.html

My Server.js file contains:

var express = require('express');
const socketIO = require('socket.io');
const path = require('path');

const PORT = process.env.PORT || 3000;
const INDEX = path.join(__dirname, '/public/index.html');

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

const server = express()
    .use((req, res) => res.sendFile(INDEX) )
    .listen(PORT, () => console.log(`Listening on ${ PORT }`));

const io = socketIO(server);

And in my index.html file I call the css and js like this:

<link rel="stylesheet" type="text/css" href="/css/styles.css" />
<script src="/js/client.js"></script>

Why use two express variables app and server

Try the following

const socketIO = require('socket.io');
const path = require('path');
const INDEX = path.join(__dirname, '/public/index.html');

const PORT = process.env.PORT || 3000;

var express = require('express');

const app = express()
    .get('/', function (req, res) {res.sendFile(INDEX)})
    .use(express.static(__dirname + '/public'))
    .listen(PORT, () => console.log(`Listening on ${ PORT }`));

const io = socketIO(app);

This will work:

const express = require('express');
const app = express();
const http = require('http').Server(app);
const socketIO = require('socket.io')(http);
const PORT = process.env.PORT || 3000;

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

http.listen(PORT, () => console.log(`Listening on ${ PORT }`));

Your code doesn't work because .use((req, res) => res.sendFile(INDEX)) always sends index.html , to any request from the client.

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