如果你打算使用 heroku 并假设你已经设置了你的 heroku 帐户并且已经安装并连接了 heroku 终端(如果你在那里遇到问题,请告诉我)
那么你需要以下:
-
Procfile - 这个文件告诉 heroku 使用什么脚本来运行你的服务器。确保将其命名为 Procfile 并且没有扩展名。
它可以包含类似下面的代码
web: yarn heroku-start - 注意这里我使用yarn 作为我的pacakge 管理器,如果你正在使用它,你可以很容易地用npm 替换它。我也打电话给heroku-start,这是我的package.json中定义的脚本
这里是pacakge.json 的示例(我只包括了重要的行)
{
...
"scripts": {
"dev": "nodemon -w src --exec \"babel-node src --presets env,stage-0\"",
"build": "babel src -s -D -d dist --presets env,stage-0",
"start": "pm2 start dist",
"prestart": "yarn -s build",
"heroku-prestart": "yarn global add pm2 && pm2 install pm2-logrotate",
"heroku-start": "node dist",
"heroku": "yarn -s build && git add . && git commit -m \"Rebuilt dist folder\" && git push heroku mj/bug/memory-leak:master",
"lint": "eslint src",
"heroku-postbuild": "echo Skip build on Heroku"
},
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-core": "^6.26.0",
"babel-eslint": "^8.0.3",
"babel-preset-env": "^1.6.1",
"babel-preset-stage-0": "^6.24.1",
"eslint": "^4.13.0"
},
"eslintConfig": {
"parserOptions": {
"ecmaVersion": 9,
"sourceType": "module"
},
"env": {
"node": true
},
"rules": {
"no-console": 0,
"no-unused-vars": [
"warn",
{
"argsIgnorePattern": "^_"
}
]
}
},
"heroku-run-build-script": true
}
我正在使用babel 来构建我的项目。请不要对我拥有的大量脚本感到不知所措,有些是无用的。但是,您应该注意脚本下的这一行 "heroku-start": "node dist" - 这是我在 heroku 上运行我的应用程序的脚本。你可以说类似node index.js 我正在使用dist 因为babel 正在构建我的应用程序以使其可用于较旧的ecma 版本,同时允许我使用新的ecma 版本,脚本build 是生成我的dist 文件夹的原因。
我还包括了我的 devDependences,以防你感兴趣。
- 你还需要
app.json - 这个文件基本上描述了你的heroku应用程序。
这是一个示例
{
"name":"myApp",
"description":"my cool app",
"repository":"https://github.com/mycoolapp/",
"logo":"http://node-js-sample.herokuapp.com/node.svg",
"keywords":["node","express","anothertag"],
"image":"heroku/nodejs"
}
完成此操作后,您可以将项目上传到 heroku,它应该可以正常运行。您可以在 heroku 和您在 github 上的 master 分支之间设置一个挂钩,以便在您推送到 maser 或合并到它时进行自动部署。
下一个:
我注意到你的代码中有问题,我不建议在 heroku 上使用 0.0.0.0,这里解释一下为什么 https://help.heroku.com/P1AVPANS/why-is-my-node-js-app-crashing-with-an-r10-error
这是你的新代码
const PORT = process.env.PORT || 5000;
app.listen(PORT, function(err) {
if (err) {
console.error(err)
} else {
console.log(`Running on port ${PORT}`)
}
}
也不要使用箭头函数,因为某些浏览器和 heroku 可能无法正确构建它(这就是我使用 babel 的原因)。
最后,这是一个关于在 heroku 上创建 nodejs 应用程序的好教程。
https://appdividend.com/2018/04/14/how-to-deploy-nodejs-app-to-heroku/
祝你好运。