Home About
React , Node.js

React でサーバーから json を取得してレンダリング

React でサーバとデータ連携する方法を調査中。 取り急ぎ、サーバから json を取得してそれを React でレンダリングするところまでのメモ。 ポイントは、React のFAQ に書いてあります。

使用した環境は以下の通り:

$ node --version
v16.15.0
$ npm -version
8.5.5
$ npx -version
8.5.5

まずはローカル環境でサーバーとクライアントを両方実装します。

サーバー

Express を使って、簡単な json を返すだけのサーバーを用意します。

プロジェクトを作成して expresscors を入れます。

$ mkdir my-server
$ cd my-server
$ npm init -y
$ npm install express --save
$ npm install cors

cors は クロスドメイン通信 対策用です。

index.js を実装。

const express = require('express');
const cors = require('cors');

const app = express();
app.use(cors());
app.use(express.json());

app.get('/', (req, res)=>{
    const jsonString = '{"message":"Hello, World!"}';
    const jsonObject = JSON.parse(jsonString);
    res.status(200).json( jsonObject );
});

const port = 8000;
app.listen(port);
console.log(`my server is up. port=${port}`);

起動:

$ node index.js
my server is up. port=8000

ブラウザで http://localhost:8000/ にアクセスすると {"message":"Hello, World!"} と表示されます。

React クライアントの実装

雛形の react プロジェクトを用意します。

$ npx create-react-app my-client
$ cd my-client

雛形で生成された src/App.js を以下のように書き換えます。

function App() {
    fetch('http://localhost:8000/').then( (res) => res.json()).then( (jsonObject)=> {
        console.log(jsonObject.message);
    });

    return (
          <div>Hello</div>
    );
}

export default App;

まずは小手試しです。 先程作成した my-server にアクセスして json を取得しますが、それを console.log に出すコードです。

実行してみます。

$ npm start

ブラウザで http://localhost:3000/ にアクセスすると Hello と表示されます。 console ログを見ると Hello, World! と出力されています。

これでブラウザで動いているクライアントがサーバから json をゲットできるところまではできています。

今度はこれをブラウザに表示させてましょう。 そのために、MessageComponent を用意します。

これは、React のFAQ を写経したようなものです。詳しくはそちらをご覧ください。

index.js を以下のように書き換えます。

import React from 'react';

class MessageComponent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            error: null,
            isLoaded: false,
            jsonObject: null};
    }

    componentDidMount() {
        fetch('http://localhost:8000/').then( (res) => res.json()).then( (jsonObject)=> {
            this.setState({
                isLoaded: true,
                jsonObject: jsonObject});
        }, (error)=> {
            this.setState({
                error: error,
                isLoaded: true,
                jsonObject: {}});
        });
    }

    render() {
        if( this.state.error ){
            return (<div>Error: {this.state.error.message}</div>);
        }
        else if (!this.state.isLoaded) {
            return (<div>Loading...</div>);
        }
        else {
            return (
                <div>{this.state.jsonObject.message}</div>
            );
        }
    }
}

function App() {
    return (
        <MessageComponent />
    );  
}

ブラウザに戻って http://localhost:3000/ にアクセスすると...

React Hello, World! with JSON

できました。

これでサーバーから供給した json を React でレンダリングすることができるようになりました。

Liked some of this entry? Buy me a coffee, please.