簡單卻也實用。
簡述
這裡會以 reqres 這個 API 來做基本的串接練習:
GET
取得使用者資料
POST
新增使用者資料
DELETE
刪除使用者資料
PATCH
修改使用者資料
原始碼
GET:
1 2 3 4 5 6 7
| const request = require('request')
const { argv } = require('process')
request(`https://reqres.in/api/users/${argv[2]}`, (error, response, body) => console.log(JSON.parse(body)) )
|
POST:
1 2 3 4 5 6 7 8 9 10 11 12
| const request = require('request')
request.post( { url: `https://reqres.in/api/users`, form: { name: 'PeaNu', job: 'F2E' } }, (error, response, body) => console.log(body) )
|
response:
1
| {"name":"PeaNu","job":"F2E","id":"204","createdAt":"2022-01-03T13:55:49.725Z"}
|
DELETE:
1 2 3 4 5 6 7 8
| const request = require('request')
request.delete('https://reqres.in/api/users/2', (error, response, body) => { console.log(response.statusCode) console.log('body:', body) })
|
response:
PATCH:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| const request = require('request')
request.patch( { url: 'https://reqres.in/api/users/2', form: { name: 'PeaNu', job: 'F2E' } }, (error, response, body) => { console.log(response.statusCode) console.log(body) } )
|
response:
1 2
| 200 {"name":"PeaNu","job":"F2E","updatedAt":"2022-01-04T06:33:38.211Z"}
|