Wei Wei - 28 days ago 19
Node.js Question

Using Express to serve static files, return Cannot GET?

I try to use Express to serve static files.

Here is my code:

test.js


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

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

app.listen(8080);


Here is my folder directory:

├── public
│ ├── folder1
│ │ └── many .js files
│ └── folder2
│ └── many .xml files
├── test.js

└── node_modules


My node is
6.5.0
, npm is
3.10.3


After I run
node test.js
, everything is OK. However, I open
http://localhost:8080/
, it returns
Cannot GET /

Answer

The reason why you're receiving Cannot GET / is because you do not have a route for GET / just like the error says, if you want to see what is in your /public folder you would need to make a request to http://localhost:8080/folder1or http://localhost:8080/folder2.

To have express return something besides Cannot GET / when requesting http://localhost:8080 then add the following to your test.js

app.get('/', (req, res) => {
  return res.status(200).send('This is the root of my express application');
});