Skip to content

Instantly share code, notes, and snippets.

@chuck0523
Created June 21, 2016 21:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chuck0523/ffa8e5a3e8181546f463fbb53ea32172 to your computer and use it in GitHub Desktop.
Save chuck0523/ffa8e5a3e8181546f463fbb53ea32172 to your computer and use it in GitHub Desktop.
// node6.2.2で実行するため、es2015記法
// パッケージimport
const fetch = require('node-fetch')
// get
fetch('https://github.com/')
.then((res) => res.text()) // プレーンテキスト
.then((body) => {
// githubのHTMLソースが表示される。
// console.log(body)
})
fetch('https://api.github.com/users/github')
.then((res) => res.json()) // json
.then((json) => {
// API一覧?が表示される
// console.log(json)
})
fetch('https://github.com/')
.then((res) => {
// レスポンスのメタデータを表示
// console.log(res.OK)
// console.log(res.status)
// console.log(res.statusText)
// console.log(res.headers.raw())
// console.log(res.headers.get('content-type'))
})
// post
fetch('http://httpbin.org/post', { method: 'POST', body: 'a=1'})
.then((res) => res.json())
.then((json) => {
// console.log(json)
})
// post with stream
// const resumer = require('resumer')
// const stream = resumer().queue('a=1').end()
//
// fetch('http://httpbin.org/post', { method: 'POST', body: stream })
// .then((res) => res.json())
// .then((json) => {
// console.log(json)
// })
// post with form-data
const FormData = require('form-data')
const form = new FormData()
form.append('a', 1)
fetch('http://httpbin.org/post', { method: 'POST', body: form, headers: form.getHeaders() })
.then((res) => res.json())
.then((json) => {
// console.log(json)
})
// co + yield
const co = require('co')
co(function* (){
let res = yield fetch('https://api.github.com/users/github')
let json = yield res.json()
console.log(json)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment