【问题标题】:heroku deployment with node server使用节点服务器部署heroku
【发布时间】:2016-11-19 07:32:46
【问题描述】:

我在 heroku 上的 web 应用程序部署仍然存在问题 - 返回的错误是无法加载资源错误 404。它在我的本地节点服务器上完美运行,但在推送到 heroku 时不加载 css 或 js 文件。我已经看到了几个关于 ruby​​ 的答案,但关于节点的数量有限 - 这是我的服务器代码:

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

// set the port of our application
// process.env.PORT lets the port be set by Heroku
var port = process.env.PORT || 8080;

// set the view engine to ejs
app.set('view engine', 'ejs');

// make express look in the public directory for assets (css/js/img)
app.use(express.static(__dirname + '/public'));

// set the home page route
app.get('/', function(req, res) {

    // ejs render automatically looks in the views folder
    res.render('index');
});

app.listen(port, function() {
    console.log('Our app is running on http://localhost:' + port);
});

非常感谢!

【问题讨论】:

  • 所以它不会加载你的 index.ejs 文件?或者它不会加载 CSS 或 JS?
  • prob 公共目录路径错误,尝试调试该值,可以使用 var path = require("path"); express.static(path.resolve(__dirname ,"/public")) 代替。
  • 它不会加载css或js。最初我有 index.html 但阅读了一些关于尝试将其更改为 ejs 的地方

标签: node.js heroku


【解决方案1】:

如果您的 JS 和 CSS 文件位于公共目录中,则需要修改代码以反映这一点。问题是 heroku 正在根目录中查找这些文件,而这些文件实际上位于 /public 中。

要将 /public 添加到请求 URL,您需要更改此行

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

到这里

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

您可以在related post 中了解更多信息。

【讨论】:

  • 此外,在未来,执行“heroku logs --tail”将为您提供详细的(实时)错误日志。那应该可以帮助您调试^^
  • 我添加了该更改,但在 heroku 服务器上仍然没有。我的文件结构是这个冥想应用程序 -public -views index.html index.js package.json Procfile meditate-app.herokuapp.com 这是链接,如果它有助于了解正在发生的事情。我是使用节点编码的新手,这是第一次尝试推送到 heroku,所以我不是 100% 错误日志的意思..感谢所有帮助
猜你喜欢
  • 1970-01-01
  • 2020-04-18
  • 1970-01-01
  • 2020-08-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-07
  • 2017-09-10
相关资源
最近更新 更多