其他分享
首页 > 其他分享> > 使用 fetch + React.js 调用 REST API

使用 fetch + React.js 调用 REST API

作者:互联网

JSON : Placeholder

JSON : Placeholder (https://jsonplaceholder.typicode.com/) 是一个用于测试的 REST API 网站。
以下使用 RxJS6 + React.js 调用该网站的 REST API,获取字符串以及 JSON 数据。

所有 GET API 都返回JSON数据,格式(JSON-Schema)如下:

{
  "type":"object",
  "properties": {
    "userId": {"type" : "integer"},
    "id": {"type" : "integer"},
    "title": {"type" : "string"},
    "body": {"type" : "string"}
  }
}

创建工程

# 安装 CLI
$ npm install -g create-react-app
# 创建新的应用程序 FetchExample
$ create-react-app fetch-example --scriptfs-version=react-scripts-ts
$ cd fetch-example
$ npm start

打开 Intellij IDEA, File / New / Project From Existing Sources...,然后选中工程所在文件夹
在向导的第1页选择 Create project from existing sources
完成向导后在点击 Finish 创建工程。

点击 Add Configurations, 点击 +npm
Name: React CLI Server
Scripts: start
点击 OK 完成配置。
点击 React CLI Server 启动程序。
http://localhost:3000/ 可打开网页。

TSLint

打开 tslint.json,将其改为

{
  "extends": ["tslint:recommended", "tslint-react", "tslint-config-prettier"],
  "linterOptions": {
    "exclude": [
      "config/**/*.js",
      "node_modules/**/*.ts",
      "coverage/lcov-report/*.js"
    ]
  },
  "rules": {
    "interface-name": false,
    "ordered-imports": false,
    "no-console": false,
    "object-literal-sort-keys": false,
    "member-access": false,
    "variable-name": false,
    "member-ordering": false,
    "class-name": false
  }
}

Post

在 src 文件夹下添加 post.ts,内容如下

export class Post {
  userId!: number;
  id!: number;
  title!: string;
  body!: string;
  toString(): string {
    return `Post {userId = ${this.userId}, id = ${this.id}, title = "${this.title}", body = "${this.body.replace(/\n/g, '\\n')}"}`;
  }
}

安装 react.di

react.di 是一个在 React.js 中实现 DI(依赖注入) 的包。
使用这个包需要安装 react.di 和 reflect-metadata。

$ npm install react.di@next reflect-metadata --save

打开 tsconfig.json 在 compilerOptions 中
添加关于 emitDecoratorMetadata 的设定。

    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,

post 服务

在 src 文件夹下添加 post.service.ts,内容如下

import { Injectable } from 'react.di';
import { Post } from './post';

@Injectable
export class PostService {
  private readonly baseUrl = 'http://jsonplaceholder.typicode.com/';

  constructor() {
    this.getPostAsString();
    this.getPostAsJson();
    this.getPosts(2);
    this.createPost();
    this.updatePost();
    this.deletePost();
  }

  private async getPostAsString() {
    const url = `${this.baseUrl}posts/1`;
    const result = await fetch(url);
    const data = await result.text();
    console.log(data);
  }

  private async getPostAsJson() {
    const url = `${this.baseUrl}posts/1`;
    const result = await fetch(url);
    const data = await result.json();
    const post = Object.assign(new Post(), data);
    console.log(post);
  }

  private async getPosts(n: number) {
    const url = `${this.baseUrl}posts`;
    const result = await fetch(url);
    const data = await result.json();
    (data as Post[]).slice(0, n).map(v => {
      const post = Object.assign(new Post(), v);
      console.log(post);
    });
  }

  private async createPost() {
    const url = `${this.baseUrl}posts`;
    const result = await fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        userId: 101,
        title: 'test title',
        body: 'test body',
      })
    });
    const data = await result.json();
    const post = Object.assign(new Post(), data);
    console.log(post);
  }

  private async updatePost() {
    const url = `${this.baseUrl}posts/1`;
    const result = await fetch(url, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        userId: 101,
        title: 'test title',
        body: 'test body',
      })
    });
    const data = await result.json();
    const post = Object.assign(new Post(), data);
    console.log(post);
  }

  private async deletePost() {
    const url = `${this.baseUrl}posts/1`;
    const result = await fetch(url, {
      method: 'DELETE'
    });
    const data = await result.text();
    console.log(data);
  }
}

打开 App.tsx,将其改为

import * as React from 'react';
import './App.css';

import logo from './logo.svg';
import { PostService } from './post.service';
import { Inject, Module } from 'react.di';

@Module({
  providers: [
    PostService,
  ],
})
class App extends React.Component {
  @Inject postService!: PostService;

  componentDidMount() {
    console.log(this.postService);
  }

  public render() {
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h1 className="App-title">Welcome to React</h1>
        </header>
        <p className="App-intro">
          To get started, edit <code>src/App.tsx</code> and save to reload.
        </p>
      </div>
    );
  }
}
 
export default App;

输出结果

{
  "userId": 1,
  "id": 1,
  "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
  "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}
Post {userId = 1, id = 1, title = "sunt aut facere repellat provident occaecati excepturi optio reprehenderit", body = "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"}
Post {userId = 1, id = 1, title = "sunt aut facere repellat provident occaecati excepturi optio reprehenderit", body = "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"}
Post {userId = 1, id = 2, title = "qui est esse", body = "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"}
{"params":{"userId":101,"title":"test title","body":"test body"},"id":101}
{"params":{"userId":101,"title":"test title","body":"test body"},"id":1}
{}

标签:body,const,title,userId,REST,js,React,Post,post
来源: https://www.cnblogs.com/zwvista/p/16655505.html