我在帖子Learning Node - Express Public folder not working
中遇到了类似的问题我已添加到我的server.js
app.use("public",express.static(__dirname + '/public'));
但是当我做的时候
http://localhost:8081/public/css/styles.css
http://localhost:8081/styles.css
两者都不起作用。我得到了#34;无法获得/public/css/styles.css"和"不能GET /styles.css"分别
这是我的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)
})
})
这是控制器文件夹中的index.js
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
实际上,如果我跑
http://localhost:8081/views/demo.hmtl
我会再次得到"无法加载资源:服务器响应状态为404(未找到)"
我错过了什么?
答案 0 :(得分:2)
我将以下内容添加到server.js并且它有效。
app.use('/views', express.static(path.resolve(__dirname, 'views')));
app.use('/public', express.static(path.resolve(__dirname, 'public')));