简体   繁体   中英

Express Can't find Static files

Using express and sockets to create a chat client. However I get a 404 when trying to connect to static files.

Server.js

var jade = require('jade');

var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
io.on('connection', function() {
    'use strict';
    socket.on('setPseudo', function(data) {
        socket.set('pseudo', data);
    });
    socket.on('message', function(message) {
        socket.get('pseudo', function(error, name) {
            var data = {
                'message': message,
                pseudo: name
            };
            socket.broadcast.emit('message', data);
            console.log("user " + name + " send this : " + message);
        });
    });
});
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.set("view options", {
    layout: false
});
app.use(express.static(__dirname + '/public'));

app.get('/', function(req, res) {
    'use strict';
    res.render('home.jade');
});
server.listen(4000);

In order for my application to work I need to connect to a script.js file in my /public folder. However the server seem to be unable to find it.

Update with jade file:

doctype html
html
    head
        title le Chat
        script(src='https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js')
        script(src="/socket.io/socket.io.js")
        script(src="public/script.js")
body
    div.container
        header
            h1 le Chat Meow
        input(type='text')#pseudoInput
        button#pseudoSet Set Pseudo
        div#chatEntries
        div#chatControls
            input(type='text')#messageInput
            button#submit Send

and also the folder structure:

-public > script.js
-views > home.jade
-server.js

script(src="public/script.js")更改为script(src="script.js")因为您的公用文件夹是静态文件的根目录,因此您无需将其放在html文件的路径中

Since somebody marked your other newest question about the console.readLine as a dublicate eventhough it obviously wasnt i'l answer to it here instead.

Apparently console.readLine does not work inside an IDE, eclipse for example. You will have to run the program inside the actual console for that code to work. A suggestion would be to use a buffered reader instead.

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