LoginSignup
40
22

More than 1 year has passed since last update.

[React]React×Expressで爆速環境構築[Express]

Last updated at Posted at 2021-07-17

こんにちは。ゆうじろうです。
この記事では、Reactで作成した画面からExpressで作成したAPIを叩いて、取得したデータを画面に表示するところまでを爆速で構築していきます。
つよつよJavaScriptエンジニアになりたい方は必見の書物です。

使用する環境について

まずは何がともあれ、環境構築を行います。
筆者はMacを使用しているので、ターミナルを使用しますが、Windowsの方もコマンドプロンプトやgitbashを使用していただければ同じ動作になります。

事前にinstall しておきたいのは以下3点です!

  • node.js

  • Express
npm install -g express-generator
  • create-react-app
npm install -g create-react-app

では、はじめましょう!

環境構築

では、ターミナルを開き、以下のコマンドを打ち込んでください。

まずはプロジェクトのディレクトリを作成します。

mkdir react-express
cd react-express

そして、npm initを実行

npm init -y

今回は爆速でいくので、 -yオプションで実行します。(npm initの設定を全部yesで設定するオプション)

続きまして、Expressのinstallです。

express react-express

サンプルができたら、cd で移動してnpm installです

cd react-express
npm install

ここで、nodeの便利パッケージnodemonをinstallしておきましょう。

npm install nodemon

expressとReactを同時に立ち上げないといけないので、concurrentlyをintallします。

npm install concurrently

Expressで作成したプロジェクトのuser.jsを修正します。

user.js
var express = require('express');
var router = express.Router();

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.json([{
    id: 1,
    name: "yujiro1"
  }, {
    id: 2,
    name: "yuziro2"
  }]);
});

module.exports = router;

app.jsのポート設定を記載します。app.jsの最後らへんに追記してください。

app.js
const port = process.env.PORT || 3001;
app.listen(port, () => console.log(`Server running on port ${port}`));

module.exports = app;

expressのpackage.jsonを修正します。

package.json
"scripts": {
    "start": "node ./bin/www",
    "server": "nodemon ./bin/www"
 }

クライアント側のアプリを作成していきましょう!

create-react-app client

クライアント側のpackage.jsonを開いて以下の設定をしてください。

package.json
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  },
  "proxy": "http://localhost:3001"

client側のApp.jsをExpressで作成したAPIを取得するように記載します。

App.js
import React, { useEffect,useState } from 'react';
import './App.css';

const App = () => {
 const url = "/users";
 const [users, setUsers] = useState([])

 useEffect(() => {
   fetch(url, { method: "GET" })
     .then((res) => res.json())
     .then((data) => {
       setUsers(data);
     })
     .catch((err) => {
       console.log(err);
       console.log("err");
     });
 }, []);

    return (
      <div classname="App">
        <h1>Users</h1>
        {users.map((user,index) =>
          <div key={index}>{user.name}</div>
        )}
      </div>
    );
}

export default App;

ここまできたらExpress側のpackage.jsonを追記します。

package.json
  "scripts": {
    "start": "node ./bin/www",
    "server": "nodemon ./bin/www",
    "client": "PORT=3002 npm start --prefix client",
    "dev": "concurrently \"npm run server\" \"npm run client\" "
  }

これで、npm run devとすれば完了です!

npm run dev

お疲れ様でした!

40
22
2

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
40
22