30
36

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

React + express + MySQL その1

Last updated at Posted at 2018-12-01

はじめに

表題の通り、Reactとexpress、MySQLを組み合わせて簡単なアプリケーション(の骨組み部分)を作ってみます。
上記の技術を単体として学んだものの、くっつけて動かすにはどうすればいいの?となったので作ってみた、という感じです。

私のスキルレベルとしては、

・React多少
・express多少
・MySQL入門レベル

という感じでフロント寄りというかバックエンドの経験はほぼありません。

MySQL

MySQLのセットアップは別記事にあげていますので、そちらをご確認ください。
今回はそちらで作成したデータベース(todoのリスト)を使用していきます。
データ自体はなんでもいいので適当なものをご用意ください。

express.js

まずはデータを吐き出す側を作成します。

インストール

$ npm install express

基本形

まずは単体で動作する部分だけ作ります。

/index.js
const express = require("express");
const app = express();

app.get("/", function(req, res) {
  res.send("go to /posts to see posts");
});

app.listen(4000, function() {
  console.log("Example app listening on port 4000!");
});

動作確認します。

node index.js

localhost:4000にアクセスして表示がされていればOKです。

ここで注意したいのが、ポート3000ではなく4000を使用している点です。
3000で作ってしまうとReactとバッティングしてしまうため、別にしています。

MySQLの組み込み

続けて、MySQLを読み込む記述を追加します。

index.js
const mysql = require("mysql");
const connection = mysql.createConnection({
  host: "localhost",
  user: "username",
  password: "password",
  database: "todos"
});

コネクション部分と、続けてgetを記述します。

index.js
app.get("/posts", function(req, res) {
  connection.query("select * from sample LIMIT 0, 10", function(
    error,
    results,
    fields
  ) {
    if (error) throw error;
    res.send(results);
  });
});

これでlocalhost:4000/postsにアクセスした際MySQLのデータが表示されていれば成功です。

React

続けてフロント部分を作っていきます。

インストール

create-react-appを使用してパパッと作ります。

$ npx create-react-app frontend
$ cd frontend
$ rm src/*

src内を一回空にして、index.jsだけ作ります。

frontend/index.js
import React from "react";
import ReactDOM from "react-dom";
import App from "./js/App";

ReactDOM.render(<App />, document.getElementById("root"));

コンポーネント自体はレンダーと切り離したいので別ファイルにします。

frontend/js/App.jsx
import React from "react";

export default class App extends React.Component {

  render() {
    return (
      <div>
        <h1>This is your todo list!</h1>
      </div>
    );
  }
}

ここまでで一回npm startして動作確認をします。
h1が表示されていればOKです。

データ表示部分の追加

上のコードに続けて書き足していきます。
Appクラスの記述にコンストラクタを書き足し・・・

frontend/js/App.jsx
export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { posts: [] };

    fetch("http://localhost:4000/posts")
      .then(response => response.json())
      .then(posts => this.setState({ posts }));
  }
// 略

render() 部分に、読み取ったデータの書き出し部分を追加します。

frontend/js/App.jsx
  render() {
    return (
      <div>
        <h1>This is your todo list!</h1>
        <ul>
          {this.state.posts.map(post => (
            <li>
              <h2>{post.content}</h2>
              <p>{post.appointedto}</p>
              <p>{post.duedate}</p>
            </li>
          ))}
        </ul>
      </div>
    );
  }

これで終わり・・・ではなく。。

CORS設定

今回、localhost:4000(express側)とlocalhost:3000(React側)と分けましたので
接続がCORSになっています。
このまま実行するとエラーで表示できません。

そこでexpress側に以下の記述を追加します。

index.js
app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept"
  );
  next();
});

参考
https://enable-cors.org/server_expressjs.html

これで、React側からexpress側へアクセスできるようになりました。

express、React側それぞれを立ち上げて、localhost:3000にアクセスしてみます。
データがうまく表示されていれば成功です。

 参考文献

このあたりを参考にさせていただきました。
https://blog.cloudboost.io/react-express-the-nodejs-way-of-reacting-and-expressing-7a518e4da3
https://hashnode.com/post/how-can-use-react-js-node-js-mysql-together-cjdlfbukh01vqn9wuaucmng6h

30
36
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
30
36

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?