【问题标题】:node express public folder 404 error节点快递公用文件夹404错误
【发布时间】:2016-04-10 22:14:55
【问题描述】:

我在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

两者都不起作用。我分别得到“Cannot GET /public/css/styles.css”和“Cannot 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(未找到)”

我错过了什么?

【问题讨论】:

  • 这是我设置 EJS 和公共静态的方法。 app.set("view engine", "ejs").use(express.static(__dirname+"/public"));
  • 英镑,感谢您的回复。我使用了您的代码,但错误仍然存​​在。我更新了我的帖子以显示 index.js。还有其他想法吗?

标签: node.js express


【解决方案1】:

我在 server.js 中添加了以下内容,它起作用了。

app.use('/views', express.static(path.resolve(__dirname, 'views')));
app.use('/public', express.static(path.resolve(__dirname, 'public')));

【讨论】:

    猜你喜欢
    • 2018-06-07
    • 2017-04-25
    • 2023-03-03
    • 1970-01-01
    • 2021-08-04
    • 2017-05-22
    • 2015-11-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多