1
0

More than 1 year has passed since last update.

.Net 6: WebAPI と React

Last updated at Posted at 2022-08-13

日経BP社から出ている
.NET 6 プログラミング入門 の 4.6 WebAPI と React をなぞってみました。

次のようなページを作成します。
image.png

プロジェクトの作成

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 を作成

フォルダーの構造

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

設定ファイル

"/weatherforecast" を "/api" にします。

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 のコードの変更

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 });
  }
}

サーバーの起動

dotnet run
$ 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
にアクセスします。

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

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

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

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

1
0
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
1
0