JSON Placeholder
JSON Placeholder (https://jsonplaceholder.typicode.com/) là một trang web API REST dùng để thử nghiệm. Dưới đây là cách sử dụng fetch + React.js để gọi các API của trang này, lấy về chuỗi ký tự và dữ liệu JSON.
- GET /posts/1
- GET /posts
- POST /posts
- PUT /posts/1
- DELETE /posts/1
Tất cả các API GET đều trả về dữ liệu JSON với định dạng (JSON-Schema) như sau:
{
"type": "object",
"properties": {
"userId": {"type": "integer"},
"id": {"type": "integer"},
"title": {"type": "string"},
"content": {"type": "string"}
}
}
Tạo Dự Án
# Cài đặt CLI
$ npm install -g create-react-app
# Tạo ứng dụng mới FetchAPIExample
$ npx create-react-app api-example --template typescript
$ cd api-example
$ npm start
Mở Intellij IDEA, File / Open..., rồi chọn thư mục dự án.
Nhấp vào Add Configurations, nhấp vào +npm Tên: ReactServerCLI Script: start Nhấp OK để hoàn tất cấu hình. Nhấp vào ReactServerCLI để khởi động chương trình. Truy cập http://localhost:3000/ để mở trang web.
Bài Viết
Thêm file bài viết.ts vào thư mục src, nội dung như sau:
export class Article {
userId!: number;
id!: number;
title!: string;
content!: string;
toString(): string {
return `Article {userId = ${this.userId}, id = ${this.id}, title = "${this.title}", content = "${this.content.replace(/\n/g, '\\n')}"}`;
}
}
Dịch Vụ Bài Viết
Thêm file article.service.ts vào thư mục src, nội dung như sau:
import { Article } from './article';
export class ArticleService {
private readonly baseUrl = 'https://jsonplaceholder.typicode.com/';
constructor() {
this.getArticleAsString();
this.getArticleAsJson();
this.getArticles(2);
this.createArticle();
this.updateArticle();
this.deleteArticle();
}
private async getArticleAsString() {
const url = `${this.baseUrl}posts/1`;
const result = await fetch(url);
const data = await result.text();
console.log(data);
}
private async getArticleAsJson() {
const url = `${this.baseUrl}posts/1`;
const result = await fetch(url);
const data = await result.json();
const article = Object.assign(new Article(), data);
console.log(article);
}
private async getArticles(n: number) {
const url = `${this.baseUrl}posts`;
const result = await fetch(url);
const data = await result.json();
(data as Article[]).slice(0, n).map(v => {
const article = Object.assign(new Article(), v);
console.log(article);
return article;
});
}
private async createArticle() {
const url = `${this.baseUrl}posts`;
const result = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
userId: 102,
title: 'test header',
content: 'test content',
})
});
const data = await result.json();
const article = Object.assign(new Article(), data);
console.log(article);
}
private async updateArticle() {
const url = `${this.baseUrl}posts/1`;
const result = await fetch(url, {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
userId: 102,
title: 'test header',
content: 'test content',
})
});
const data = await result.json();
const article = Object.assign(new Article(), data);
console.log(article);
}
private async deleteArticle() {
const url = `${this.baseUrl}posts/1`;
const result = await fetch(url, {
method: 'DELETE'
});
const data = await result.text();
console.log(data);
}
}
- getArticleAsString: Lấy bài viết đầu tiên, trả về chuỗi ký tự.
- getArticleAsJson: Lấy bài viết đầu tiên, trả về đối tượng bài viết.
- getArticles: Lấy n bài viết đầu tiên, trả về danh sách đối tượng bài viết.
- createArticle: Tạo một bài viết mới, trả về chuỗi ký tự.
- updateArticle: Cập nhật bài viết đầu tiên, trả về chuỗi ký tự.
- deleteArticle: Xóa bài viết đầu tiên, trả về chuỗi ký tự.
Sửa đổi App.tsx thành:
import * as React from 'react';
import './App.css';
import logo from './logo.svg';
import { ArticleService } from './article.service';
class App extends React.Component {
articleService!: ArticleService;
componentDidMount() {
this.articleService = new ArticleService();
}
public render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Chào mừng đến với React</h1>
</header>
<p className="App-intro">
Để bắt đầu, chỉnh sửa src/App.tsx và lưu để tải lại.
</p>
</div>
);
}
}
export default App;