我有我的第一个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不会绑定到本地主机。
您必须为主机传递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
在使用yeoman的angular-fullstack生成项目时,我也有同样的问题,删除IP参数对我有用。
我替换了这段代码
server.listen(config.port, config.ip, function () {
console.log('Express server listening on %d, in %s mode', config.port, app.get('env'));
});
与
server.listen(config.port, function () {
console.log('Express server listening on %d, in %s mode', config.port, app.get('env'));
});
我使用ReactJs,
如果你想上传到heroku,在你的webpack.config.js中添加这个
因为如果不加就会有错误
错误R10(引导超时)-> Web进程绑定$PORT失败
发射60秒
//webpack.config.js add code like that
const HtmlWebPackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
var server_port = process.env.YOUR_PORT || process.env.PORT || 5000;
var server_host = process.env.YOUR_HOST || "0.0.0.0";
module.exports = {
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.css$/,
use: [MiniCssExtractPlugin.loader, "css-loader"]
}
]
},
devServer: {
disableHostCheck: true,
contentBase: "./ dist",
compress: true,
inline: true,
port: server_port,
host: server_host
},
plugins: [
new HtmlWebPackPlugin({
template: "./src/index.html",
filename: "index.html"
}),
new MiniCssExtractPlugin({
filename: "[name].css",
chunkFilename: "[id].css"
})
]
};