我有我的第一个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/');
知道吗?
Heroku动态地为你的应用程序分配一个端口,所以你不能将端口设置为一个固定的数字。Heroku将端口添加到env中,因此您可以从那里拉出它。切换收听:
.listen(process.env.PORT || 5000)
这样,当您在本地测试时,它仍然会监听5000端口,但它也可以在Heroku上工作。
您可以在这里查看Node.js上的Heroku文档。