我有我的第一个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时,我得到了一个错误:
Web进程在启动后60秒内未能绑定到$PORT
当运行heroku日志时——终端中的tail。但是当我在本地运行服务器时,应用程序将按预期运行。
我在index.js文件(服务器文件)中有这个
const PORT = process.env.port || 4000
app.listen(PORT, () => {
console.log(`Server listening on port ${PORT}`)
})
但是应该有这个
const PORT = process.env.PORT || 4000
app.listen(PORT, () => {
console.log(`Server listening on port ${PORT}`)
})
使用process.env。PORT,而不是process.env。port,因为port和port显然不一样。
这是格兰桑特的功劳。
我使用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"
})
]
};
在你的包裹里。json文件,在脚本中,确保你的启动脚本包含-p $PORT。
包的示例。json(在这种情况下,为NextJS应用程序):
{
"private": true,
"scripts": {
"dev": "next dev -p 3001",
"build": "next build",
"start": "next start -p $PORT" // make sure to have -p $PORT in here
},
"dependencies": {
"typescript": "^4.3.2"
},
"devDependencies": {
"@next/eslint-plugin-next": "^11.1.2",
"@types/mongoose": "^5.11.97"
"typescript": "^4.3.2"
}
"license": "MIT"
}