LoginSignup
28
39

More than 1 year has passed since last update.

nodejs + mysql + React + ReduxでCRUDアプリを作る Part1

Last updated at Posted at 2019-07-04

概要

シンプルなCRUD(create, read, update, delete)アプリをデータベースはmysql, フロントエンドはReact + Reduxで作ってみます.
このPart1ではmysqlの設定, node.jsでAPIサーバーの作成まで行います.

mysqlのインストール, 接続

まずmysqlをインストールします.

$ brew update
$ brew install mysql

インストールが終わったら内容を見てみます.

$ brew info mysql

次にデータベースを起動します. 起動はmysql.server start(停止はmysql.server stop)

$ mysql.server start
Starting MySQL
. SUCCESS! 

パスワードを設定しておきます.

$ mysql_secure_installation

聞かれることは基本的にYesで答えます. パスワードは覚えておきましょう.
設定が終わったら接続します.

$ mysql -uroot -p
Enter password:[設定したパスワード]

接続はexitで抜けれます.

mysqlでDB, テーブルの作成

mysqlに接続した状態でまずDBを作成します.

mysql> CREATE DATABASE sample;

DBの作成結果を確認します.

mysql> show databases;

作成したDBを使用可能にします.

mysql> use sample;

次にテーブルを作成します.
idカラムにはauto_incrementを設定しておきます.
nameとstatusにはnot nullを設定します.
nameはuniqueにしておきます.

mysql> create table user (id int auto_increment not null primary key, name varchar(10) not null unique, status varchar(10) not null);

テーブルの作成結果を確認します.

mysql> show tables;
+------------------+
| Tables_in_sample |
+------------------+
| user             |
+------------------+
1 row in set (0.01 sec)

テーブルの定義を確認する

mysql> desc user;
+--------+-------------+------+-----+---------+----------------+
| Field  | Type        | Null | Key | Default | Extra          |
+--------+-------------+------+-----+---------+----------------+
| id     | int(11)     | NO   | PRI | NULL    | auto_increment |
| name   | varchar(10) | NO   | UNI | NULL    |                |
| status | varchar(10) | NO   |     | NULL    |                |
+--------+-------------+------+-----+---------+----------------+
3 rows in set (0.00 sec)

ユーザーを作成します.
nodeがユーザー, localhostがホストになります.
パスワードは後で使うので覚えておきましょう.

mysql> create user 'node'@'localhost' identified with mysql_native_password by 'パスワード';

ユーザーの作成結果を確認します.

mysql> SHOW GRANTS for 'node'@'localhost';

参照可能テーブルを指定します.

mysql> GRANT ALL ON sample.* to node@localhost;

権限の付与結果を確認します.

mysql> SHOW GRANTS for 'node'@'localhost';

試しにサンプルデータを作成してみます.

mysql> insert into user(name, status) values('Katsuomi', 'student');

確認してみます.

mysql> select * from staff;
+----+----------+---------+
| id | name     | status  |
+----+----------+---------+
|  1 | Katsuomi | student |
+----+----------+---------+
1 row in set (0.01 sec)

もう1人作ってみます

mysql> insert into user(name, status) values('Junki', 'student');

確認します.

mysql> select * from user;
+----+----------+---------+
| id | name     | status  |
+----+----------+---------+
|  1 | Katsuomi | student |
|  2 | Junki    | student |
+----+----------+---------+
2 rows in set (0.00 sec)

無事にidがauto_incrementされていることを確認しました.

APIサーバーの作成

適当にディレクトリを作ってserver.jsを作り, そこに書いていきます.

$ mkdir crud-node & cd crud-node
$ npm init -y
$ npm i mysql express body-parser
server.js
const express = require('express');
const mysql = require('mysql');
const bodyParser = require('body-parser');
const cors = require('cors')({origin: true});
const app = express();
app.use(bodyParser.json());
app.use(cors);

const client = mysql.createConnection({
    host: 'localhost',
    user: 'node',
    password: '******',
    port : 3306,
    database: 'sample'
});

client.connect(function (err) {
    if (err) {
        console.error('error connecting: ' + err.stack);
        return;
    }
    console.log('connected as id ' + client.threadId);
});

// read 
app.get('/user', (req, res) => {
    client.query('SELECT * from user;', (err, rows, fields) => {
        if (err) throw err;
      
        res.send(rows);
    });
});

// create 
app.post('/user/create', (req, res) => {
    const name = req.body.name;
    const status = req.body.status;
    client.query('INSERT INTO user SET ?', {name: name, status: status}, (err, result) => {
        if (err) throw err;
        res.send(result);
    })
});

// update 
app.put('/user/update', (req, res) => {
    const id = req.body.id;
    const status = req.body.status;
    client.query('UPDATE user SET status = ? WHERE id = ?', [status, id], (err, result) => {
        if (err) throw err;
        client.query('SELECT * from user;', (err, rows, fields) => {
            if (err) throw err;
            res.send(rows);
        });
    })
});

// delete 
app.delete('/user/delete', (req, res) => {
    const id = req.body.id;
    client.query(`DELETE FROM user WHERE id = ?`, [id], (err, result) => {
        if (err) throw err;
        client.query('SELECT * from user;', (err, rows, fields) => {
            if (err) throw err;
            res.send(rows);
        });
    });
});

app.listen(3001, () => console.log('Listening on port 3001!'))

それではcurlでテストしていきましょう.

作成

$ curl -X POST -H "Content-Type:application/json" http://localhost:3001/user/create  -d '{"name":"taro", "status": "adult"}'

更新

$ curl -X PUT -H "Content-Type:application/json" http://localhost:3001/user/update  -d '{"name":"taro", "status": "student"}'

閲覧

curl http://localhost:3001/user

削除

$ curl -X DELETE -H "Content-Type:application/json" http://localhost:3001/user/delete  -d '{"id":1}'

最後に

Part2ではReact + Reduxでフロントエンドを作っていきます.
Part2はこちら

Happy Hacking :sunglasses: !

28
39
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
28
39