Home About
React , Node.js

React で入力したテキストをサーバーに json にして送信

React でサーバとデータ連携する方法を調査中。 取り急ぎ、前回はサーバから json を取得したので、今度はPOSTで送信してみます。 送信する内容はフォームに入れた文字列とします。 React でフォーム処理する部分はこのドキュメントを参照のこと。

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

サーバー

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.post('/', (req, res)=>{
    const jsonObj = req.body;
    console.log( JSON.stringify(jsonObj) );

    const jsonString = `{"message": "Hello, ${jsonObj.name}!"}`;
    res.status(200).json( JSON.parse(jsonString) );
});

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

JSONがPOSTされたら Hello, POSTされたJSONに含まれている名前! を返します。

起動:

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

React クライアントの実装

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

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

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

import React from 'react';

class NameFormAndMessage extends React.Component {
    constructor(props){
        super(props);

        this.state = {
            value: '',
            message: ''
        };

        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    handleChange(event){
        const newState = {
            value: event.target.value,
            message: this.state.message
        };
        this.setState( newState );
    }

    handleSubmit(event){
        //console.log(`a name was submitted: ${this.state.value}`);
        event.preventDefault();

        const requestOptions = {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ name: `${this.state.value}` })
        };
        fetch('http://localhost:8000/', requestOptions)
            .then(response => response.json())
            .then(jsonObj => {
                console.log(jsonObj.message);
                const newState = {
                    value: this.state.value,
                    message: jsonObj.message
                };
                this.setState(newState);
            });
    }

    render(){
        return (
            <>
                <div>
                    <form onSubmit={this.handleSubmit}>
                        <label>
                            Name:
                            <input type="text" value={this.state.value} onChange={this.handleChange} />
                        </label>
                        <input type="submit" value="Submit"/>
                    </form>
                </div>
                <div>
                    <p>{this.state.message}</p>
                </div>
            </>
        );
    }
}

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

export default App;

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

実行してみます。

$ npm start

ブラウザで http://localhost:3000/ にアクセスして Name: のフォームに World と文字列を入力してから Submit します。

React Hello, World! with JSON

デバッグのコンソールをみると Hello, World! と出力されます。

これでウェブクライアントから送信した内容をサーバーにPOSTすることができました。

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