前提
如果想要在雲端運作服務,heroku是個不錯的選擇。
把代碼上傳到Github上
資料庫選用Mongodb atlas
把資料連接配接到雲端資料庫,這裡不做詳細介紹。
代碼修改準備部署
npm i compression
用來壓縮http協定
npm i helmet
用來保護web免受攻擊
建立個檔案夾作為Production配置
prod.js
//for production environment
const helmet = require('helmet');
const compression = require('compression');
module.exports=function (app) {
app.use(helmet());
app.use(compression());
}
在index.js檔案中添加
然後在package.json檔案中添加
"scripts": {
"start": "node index.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"engines": {"node":"v11.7.0"},
node版本為本機對應版本
這時使用
npm start
就是使用
"start": "node index.js"
連接配接github并部署
- 建立app,并連接配接gtihub
- 并允許自動部署
- Open the Settings tab and locate Buildpacks and click “Add buildpack”. 選擇Node.js
-
go back to the Deploy tab, and click Deploy Branch at the bottom.
然後會部署,等到部署完成會提示成功!!!
然後可以輸入連接配接進行測試,如下

另有文章參考非常詳細:How to deploy a NodeJS app to Heroku from Github (without installing Heroku on your machine)
連接配接Github很友善進行部署,當然也可以自己使用heroku cli部署需要安裝heroku。
安裝heroku,下載下傳對應版本,并檢查
heroku -v
然後
heroku login
登入