Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express-js can't GET my static files, why?

I've reduced my code to the simplest express-js app I could make:

var express = require("express"),     app = express.createServer(); app.use(express.static(__dirname + '/styles')); app.listen(3001); 

My directory look like this:

static_file.js /styles   default.css 

Yet when I access http://localhost:3001/styles/default.css I get the following error:

Cannot GET / styles / default.css 

I'm using express 2.3.3 and node 0.4.7. What am I doing wrong?

like image 640
Kit Sunde Avatar asked May 07 '11 21:05

Kit Sunde


People also ask

Can Express 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.

Which express JS function is used to serve static files?

To serve static files such as images, CSS files, and JavaScript files, use the express. static built-in middleware function in Express. The root argument specifies the root directory from which to serve static assets.

How do I serve a static file in node JS?

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.


2 Answers

Try http://localhost:3001/default.css.

To have /styles in your request URL, use:

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

Look at the examples on this page:

//Serve static content for the app from the "public" directory in the application directory.      // GET /style.css etc     app.use(express.static(__dirname + '/public'));  // Mount the middleware at "/static" to serve static content only when their request path is prefixed with "/static".      // GET /static/style.css etc.     app.use('/static', express.static(__dirname + '/public')); 
like image 167
Giacomo Avatar answered Sep 28 '22 20:09

Giacomo


I have the same problem. I have resolved the problem with following code:

app.use('/img',express.static(path.join(__dirname, 'public/images'))); app.use('/js',express.static(path.join(__dirname, 'public/javascripts'))); app.use('/css',express.static(path.join(__dirname, 'public/stylesheets'))); 

Static request example:

http://pruebaexpress.lite.c9.io/js/socket.io.js 

I need a more simple solution. Does it exist?

like image 45
David Miró Avatar answered Sep 28 '22 21:09

David Miró