我有我的第一个node.js应用程序(本地运行良好)-但我无法通过heroku部署它(第一次w/ heroku也是如此)。代码如下。SO不让我写这么多代码,所以我只想说在我的网络中本地运行代码也没有问题。
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 bash进程中,使用选项解析器(如yargs)将$PORT的值传递给节点应用程序。
下面是一个示例,说明如何做到这一点。在脚本对象上,在包内。添加一个启动方法"node server——port $ port "。
在你的服务器文件中,使用yargs从start方法的port选项(——port $ port)中获取值:
const argv = require('yargs').argv;
const app = require('express')();
const port = argv.port || 8081;
app.listen(argv.port, ()=>{
console.log('Probably listening to heroku $PORT now ', argv.port); // unless $PORT is undefined, in which case you're listening to 8081.
});
现在当你的应用程序启动时,它将绑定到动态设置的值$PORT。
对于那些同时传递端口和主机的程序,请记住Heroku不会绑定到本地主机。
您必须为主机传递0.0.0.0。
即使您使用了正确的端口。我们必须做出这样的调整:
# port (as described above) and host are both wrong
const host = 'localhost';
const port = 3000;
# use alternate localhost and the port Heroku assigns to $PORT
const host = '0.0.0.0';
const port = process.env.PORT || 3000;
然后你可以像往常一样启动服务器:
app.listen(port, host, function() {
console.log("Server started.......");
});
你可以在这里看到更多细节:https://help.heroku.com/P1AVPANS/why-is-my-node-js-app-crashing-with-an-r10-error
当Heroku在服务器上绑定端口或主机名失败时发生错误。监听(port, [host], [backlog], [callback])。
Heroku需要的是.listen(process.env. port)或.listen(process.env. port)。港口,“0.0.0.0”)
所以更一般地,为了支持其他环境,使用这个:
var server_port = process.env.YOUR_PORT || process.env.PORT || 80;
var server_host = process.env.YOUR_HOST || '0.0.0.0';
server.listen(server_port, server_host, function() {
console.log('Listening on port %d', server_port);
});
在我的例子中,端口和主机都不是问题。index.js被分成了两个文件。server.js:
//server.js
const express = require('express')
const path = require('path')
const app = express()
app.use(express.static(path.resolve(__dirname, 'public')));
// and all the other stuff
module.exports = app
//app.js
const app = require('./server');
const port = process.env.PORT || 3000;
app.listen(port, '0.0.0.0', () => {
console.log('Server is running s on port: ' + port)
});
从包中。我们运行node app。js。
显然这就是问题所在。一旦我将两者合并到一个文件中,Heroku应用程序就会按预期部署。