1

I got a very similar problem with this post Learning Node - Express Public folder not working

I added to my server.js

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

But when I do

http://localhost:8081/public/css/styles.css
http://localhost:8081/styles.css

Neither works. I got "Cannot GET /public/css/styles.css" and "Cannot GET /styles.css" respectively.

Here is my server.js

var express = require('express')
    , cors = require('cors')
    , app = express()
    , mongoose = require('mongoose')
    , models = require('./models')
    , bodyParser = require('body-parser')
    , controllers = require('./controllers')
    , port = 8081//process.env.PORT || 3000

// Config
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cors());

app.set('views', __dirname + '/views')
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);

app.use("public",express.static(__dirname + '/public'));
app.use('/', controllers);
mongoose.set('debug', true);
mongoose.connect('mongodb://localhost/db', function (err) {
    if (err) throw err;

    console.log("mongoose connected")
    var server = app.listen(port, function () {
        var host = server.address().address
        var port = server.address().port
        console.log("RESTful Web Services listening at http://%s:%s", host, port)
    })
})

Here is the index.js in the controller folder

var express = require('express')
  , router = express.Router()
  , users = require('./api/users.js')

router.use('/api/user', users);

router.get('/', function (req, res) {
    res.render('index.html')
})
//router.use(express.static('public'));
//router.use(express.static('views'));

router.get('/views/demo', function (req, res) {
    res.sendFile('/views/demo.html')
})

module.exports = router

Actually, if I run

http://localhost:8081/views/demo.hmtl

I would again get "Failed to load resource: the server responded with a status of 404 (Not Found)"

What did I miss?

Community
  • 1
  • 1
Shawn
  • 5,130
  • 13
  • 66
  • 109
  • Here's how I setup EJS and public static. `app.set("view engine", "ejs").use(express.static(__dirname+"/public"));` – Sterling Archer Apr 10 '16 at 22:23
  • Sterling, thanks to the reply. I used your code and the error persists. I updated my post to show index.js. Any other idea? – Shawn Apr 10 '16 at 22:50

1 Answers1

3

I added the following to the server.js and it worked.

app.use('/views', express.static(path.resolve(__dirname, 'views')));
app.use('/public', express.static(path.resolve(__dirname, 'public')));
Shawn
  • 5,130
  • 13
  • 66
  • 109