postman
- Chrome拡張を追加する
jsonplaceholder
テスト用のAPIを返すサービスを使ってpostmanを試用してみる
GETで以下を入力し、Sendを押す
http://jsonplaceholder.typicode.com/posts
- テスト用のjsonが返ってくる
json-serverインストール
npm install -g json-server
サンプル
create-react-app test
db.jsonの追加
db.json
{
"posts": [
{
"id": 1,
"title": "タイトル",
"body": "こんにちは"
}
]
}
json-server起動
json-server --watch db.json --port 8888
postmanを使ってAPIにアクセスしてみる(GETとPOST)
GET (データ取得してみる)
- db.jsonのデータが取れている。
POST (投稿してみる)
- パラメーターを入力。(以下でSendを押す)
- 入力したパラメータがテーブルに書き込まれたことが確認できる
ローカルAPIをJSから使ってみる
index.js
index.js
import React from 'react';
import ReactDOM from 'react-dom';
const url = "http://localhost:8888/posts";
class Form extends React.Component {
constructor(props) {
super(props);
this.state= {
title: "",
body: ""
}
this.handleTitleChange = this.handleTitleChange.bind(this);
this.handleBodyChange = this.handleBodyChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleTitleChange(event) {
console.log("state:title ", this.state.title);
this.setState({title: event.target.value});
}
handleBodyChange(event) {
console.log("state:body ", this.state.body);
this.setState({body: event.target.value});
}
handleSubmit(event) {
console.log("handleSubmit");
//alert('送信内容:' + this.state.title + this.state.body);
event.preventDefault();
this.props.addPost(this.state.title, this.state.body);
}
render() {
return(
<form onSubmit={this.handleSubmit}>
<div>
<label>
タイトル:
<input type="text" value={this.state.title} onChange={this.handleTitleChange} />
</label>
</div>
<div>
<label>
本文:
<input type="text" value={this.state.body} onChange={this.handleBodyChange} />
</label>
</div>
<div>
<input type="submit" value="追加" />
</div>
</form>
);
}
}
class Posts extends React.Component {
constructor(props) {
super(props);
this.state = {
posts: this.props.posts
};
this.add = this.add.bind(this);
}
add(title, body) {
console.log("add is called");
console.log("title", title);
console.log("body", body);
fetch(url, {
method: 'post',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: "title=" + title + "&body=" + body
}).then(function(response) {
return response.json();
}).then(function(json){
console.log(json);
let count = this.state.posts.length + 1;
this.state.posts.push({
title: json.title,
body: json.body,
id: count
});
this.setState(this.state);
}.bind(this));
}
render (){
return(
<section>
{this.state.posts.map(function(post,index){
return(
<section key={post.id}>
<h1>{post.title}</h1>
<p>{post.body}</p>
</section>
);
}.bind(this))}
<Form addPost={this.add} />
</section>
);
}
}
fetch(url).then(function(response){
return response.json();
}).then(function(json) {
console.log(json);
ReactDOM.render(
<Posts posts={json} />,
document.getElementById('root')
);
});
create-react-appを起動
npm start