.Net 6: WebAPI と React

日経BP社から出ている
[.NET 6 プログラミング入門](https://github.com/moonmile/net6-samples) の 4.6 WebAPI と React をなぞってみました。

次のようなページを作成します。
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/179446/3f111c7f-0803-e9a0-7da1-81f279c39961.png)

プロジェクトの作成

```bash
dotnet new react --name Web02
cd Web02
rm WeatherForecast.cs
rm Controllers/WeatherForecastController.cs
mkdir Models
```

## API の作成

次は、
>Models/Books.cs
>Controllers/BooksControllers.cs

こちらのものと同じです。
[.Net 6: WebAPI を作成](https://qiita.com/ekzemplaro/items/b9dc76d5e90fbf526941)

## フォルダーの構造

```text
$ tree -L 1
.
├── ClientApp
├── Controllers
├── Models
├── Pages
├── Program.cs
├── Properties
├── Web02.csproj
├── appsettings.Development.json
├── appsettings.json
└── obj
```

## 設定ファイル
"/weatherforecast" を "/api" にします。

```json:ClientApp/src/setupProxy.js
const { createProxyMiddleware } = require('http-proxy-middleware');
const { env } = require('process');

const target = env.ASPNETCORE_HTTPS_PORT ? `https://localhost:${env.ASPNETCORE_HTTPS_PORT}` :
  env.ASPNETCORE_URLS ? env.ASPNETCORE_URLS.split(';')[0] : 'http://localhost:39792';

const context =  [
  "/api",
//  "/weatherforecast",
];

module.exports = function(app) {
  const appProxy = createProxyMiddleware(context, {
    target: target,
    secure: false,
    headers: {
      Connection: 'Keep-Alive'
    }
  });

  app.use(appProxy);
};
```

## React のコードの変更

```js:ClientApp/src/components/FetchData.js
import React, { Component } from 'react';

export class FetchData extends Component {
  static displayName = FetchData.name;

  constructor(props) {
    super(props);
    this.state = { forecasts: [], loading: true };
  }

  componentDidMount() {
    this.populateWeatherData();
  }

  static renderForecastsTable(forecasts) {
    return (
      <table className='table table-striped' aria-labelledby="tabelLabel">
        <thead>
          <tr>
            <th>Id</th>
            <th>Khm</th>
            <th>タイトル</th>
            <th>ドイツ語名</th>
          </tr>
        </thead>
        <tbody>
          {forecasts.map(forecast =>
            <tr key={forecast.id}>
              <td>{forecast.id}</td>
              <td>{forecast.khm}</td>
              <td>{forecast.title}</td>
              <td>{forecast.deutsch}</td>
            </tr>
          )}
        </tbody>
      </table>
    );
  }

  render() {
    let contents = this.state.loading
      ? <p><em>Loading...</em></p>
      : FetchData.renderForecastsTable(this.state.forecasts);

    return (
      <div>
        <h1 id="tabelLabel" >グリムの昔話</h1>
        <p>This component demonstrates fetching data from the server.</p>
        {contents}
      </div>
    );
  }

  async populateWeatherData() {
//    const response = await fetch('weatherforecast');
    const response = await fetch('api/books');
    const data = await response.json();
    this.setState({ forecasts: data, loading: false });
  }
}
```

## サーバーの起動

```bash
dotnet run
```

```text
$ dotnet run
info: Microsoft.Hosting.Lifetime[14]
      Now listening on: https://localhost:7021
info: Microsoft.Hosting.Lifetime[14]
      Now listening on: http://localhost:5002
info: Microsoft.Hosting.Lifetime[0]
      Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
      Hosting environment: Development
info: Microsoft.Hosting.Lifetime[0]
      Content root path: /home/uchida/tmp/dotnet/react/Web02/
```

一度、クライアントで、
https://localhost:7021
にアクセスします。

すると、サーバーのコンパイルが進み次のメッセージが出ます。

```text
Compiled successfully!

You can now view web02 in the browser.

  Local:            https://localhost:44415
  On Your Network:  https://192.168.1.4:44415

Note that the development build is not optimized.
To create a production build, use npm run build.

webpack compiled successfully
info: Microsoft.AspNetCore.SpaProxy.SpaProxyMiddleware[0]
      SPA proxy is ready. Redirecting to https://localhost:44415.
info: Microsoft.AspNetCore.SpaProxy.SpaProxyLaunchManager[0]
      SPA development server running at 'https://localhost:44415'
```

そうしたら、クライアントで、
https://localhost:44415
にアクセスします。
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/179446/0b1bf012-881b-b30a-2fe1-bd61cecd888d.png)

Fetch Data をクリックすれば、冒頭の表示がでます。

ポート番号、7021,44415 はランダムです。