zwvista

导航

使用 fetch + React.js 调用 REST API

JSON : Placeholder

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

  • GET /posts/1
  • GET /posts
  • POST /posts
  • PUT /posts/1
  • DELETE /posts/1

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

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

创建工程

# 安装 CLI
$ npm install -g cra-template-typescript
# 创建新的应用程序 FetchExample
$ npx create-react-app fetch-example --template typescript
$ cd fetch-example
$ npm start

打开 Intellij IDEA, File / Open...,然后选中工程所在文件夹

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

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')}"}`;
  }
}

post 服务

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

import { Post } from './post';

export class PostService {
  private readonly baseUrl = 'https://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);
      return 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);
  }
}
  • getPostAsString 方法取出第1个Post,返回字符串
  • getPostAsJson 方法取出第1个Post,返回Post对象
  • getPosts 方法取出前n个Post,返回n个Post对象
  • createPost 方法创建1个Post,返回字符串
  • updatePost 方法更新第1个Post,返回字符串
  • deletePost 方法删除第1个Post,返回字符串

打开 App.tsx,将其改为

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

import logo from './logo.svg';
import { PostService } from './post.service';

class App extends React.Component {
  postService!: PostService;

  componentDidMount() {
    this.postService = new 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}
{}

posted on 2022-09-04 17:22  zwvista  阅读(82)  评论(0编辑  收藏  举报