Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS won't serve static files, even when using express.static

I have something along the lines of the following:

var request = require('request'),
    express = require('express');

var app = express.createServer();

var port = process.env.PORT || 8080;

app.configure(function(){
    app.set("view options", { layout: false, pretty: true });
    app.use(express.favicon());
    app.use("/public", express.static(__dirname + '/public'));
    }
);

app.listen(port);

// Routes
app.get('/', function(req, resp){
    resp.render('index.jade', {pageTitle: 'Some title'});
});

Yet, when I visit /public/myfile.css for example, I still get:

Cannot GET /public/myfile.css My index.jade templates cannot seem to call the files either

Why is this?

like image 760
Alex Avatar asked Mar 10 '12 12:03

Alex


People also ask

Does Express allow you to serve static files?

Express offers a built-in middleware to serve your static files and modularizes content within a client-side directory in one line of code.

How do I serve a static file in NodeJS?

In your node application, you can use node-static module to serve static resources. The node-static module is an HTTP static-file server module with built-in caching. First of all, install node-static module using NPM as below. After installing node-static module, you can create static file server in Node.

Why Express app and server files kept separately?

Applying a similar concept to the project structuring of Express, the separation of the application logic from the server allows the code to be modular and follow a MVC (Model-View-Controller) model. The separation is essential to reduce coupling and to encapsulate and abstract the inside logic of application.

What does Express static () return?

use() function executes middleware in order. The express. static() middleware returns an HTTP 404 if it can't find a file, so that means you should typically call app.


1 Answers

I don't think supplying the path like that is supported:

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

Try this, and look for your public files in the root:

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

So /public/myfile.css becomes /myfile.css.

like image 149
Linus Thiel Avatar answered Oct 19 '22 10:10

Linus Thiel