我有我的第一个 node.js 应用程序(在本地运行良好)-但我无法通过 heroku 部署它(也是第一次使用 heroku)。代码如下。所以不允许我写这么多代码,所以我只想说在本地以及在我的网络中运行代码没有问题。
var http = require('http');
var fs = require('fs');
var path = require('path');
http.createServer(function (request, response) {
console.log('request starting for ');
console.log(request);
var filePath = '.' + request.url;
if (filePath == './')
filePath = './index.html';
console.log(filePath);
var extname = path.extname(filePath);
var contentType = 'text/html';
switch (extname) {
case '.js':
contentType = 'text/javascript';
break;
case '.css':
contentType = 'text/css';
break;
}
path.exists(filePath, function(exists) {
if (exists) {
fs.readFile(filePath, function(error, content) {
if (error) {
response.writeHead(500);
response.end();
}
else {
response.writeHead(200, { 'Content-Type': contentType });
response.end(content, 'utf-8');
}
});
}
else {
response.writeHead(404);
response.end();
}
});
}).listen(5000);
console.log('Server running at http://127.0.0.1:5000/');
任何想法 ?
原文由 user428900 发布,翻译遵循 CC BY-SA 4.0 许可协议
Heroku 动态地为您的应用程序分配一个端口,因此您不能将端口设置为固定数字。 Heroku 将端口添加到环境中,因此您可以从那里拉出它。切换你的听这个:
这样,当您在本地测试时,它仍然会监听端口 5000,但它也可以在 Heroku 上运行。 重要说明- PORT 字必须大写。
您可以在 此处 查看有关 Node.js 的 Heroku 文档。