天天看点

使用Heroku将代码部署到云端服务器

前提

如果想要在云端运行服务,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.

    然后会部署,等到部署完成会提示成功!!!

然后可以输入连接进行测试,如下

使用Heroku将代码部署到云端服务器

另有文章参考非常详细: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

登录

继续阅读