LoginSignup
6
4

More than 3 years have passed since last update.

Node.js & Express & MySQL & React でTODOリスト Herokuにデプロイ編

Posted at

はじめに

前回の続きです。
https://qiita.com/hcr1s/items/0e5970c5af496c221a24

今回は、前回作成したAPIをHerokuへデプロイしていきます。

前提

今回は、Herokuのアカウントを所持しており、クレジット登録していることを前提とします。

Heroku app作成

まずは、git initやheroku createを実行していきます。

# 既にgit initしている場合は省略
$ git init
$ git add .
$ git commit -m 'commit名'

# herokuでアプリ作成
$ heroku create アプリ名
$ heroku git:remote -a アプリ名

$ git push heroku master

とりあえず本番環境へpushは完了です。

MySQL

本番環境でMySQLへ接続するための設定を行なっていきます。

$ heroku addons:add cleardb

Herokuでは、cleardbというクラウドサービスのMySQLを使用できます。

$ heroku config | grep CLEARDB_DATABASE_URL
↓
CLEARDB_DATABASE_URL: mysql://user名:password@host名/database名?reconnect=true

このコマンドで、必要なデータベースの情報を取得できます。
この情報をconfigに設定していきます。

$ heroku config:set DATABASE_URL='mysql://*********?reconnect=true'

mysql://のあとは、grepの結果をそのままペースとしてください。

以上でcleardbの設定は終了です。

index.jsの編集

実際にプログラムに必要なコードを記述していきます。
まずは、前回も書いたcreateConnectionの編集をしていきます。

index.js
--- 省略 ---

const databaseName = 'database名'
const connection = mysql.createConnection({
  host: host名,
  user: user名,
  password: 'password',
  database: 'database名'
})

--- 省略 ---

中身に関しては、MySQLの設定時のgrepを参考に記述していきます。
そして、必要なデータベースやテーブルが存在しない場合、つまり初回に限り実行されるSQLを記述します。

index.js
connection.query('create database if not exists ??;', databaseName)
connection.query('use ??', databaseName)
connection.query('create table if not exists todo_list(id int auto_increment, name varchar(255), isDone boolean, index(id))')

前回も書きましたが、SQL文にフィールドを使用する際は??と記述します。

以上で、コードの編集も終了です。

package.jsonの編集

Herokuにデプロイした際に、package.jsonに記述がないとnpm startが実行されてしまうので編集します。

package.json
{
  "name": "todo-api",
  "version": "1.0.0",
  "description": "",
  "engines":{
    "node": "12.13.0",
    "npm": "6.12.0"
  },
  "main": "index.js",
  "scripts": {
    "start" : "node index.js"
  },
--- 省略 ---

デプロイ

最後にデプロイをして終了です。

実際に使ってみましょう。

スクリーンショット 2019-12-02 18.28.30.png

実際にPOSTを送ってみた際のスクショです。
いい感じですね。

終わり

次回は、このAPIを使用してTODOアプリを開発していきます。
何か間違いがある際はおしらせください!

6
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
4