RestFul API
GET 取得资料POST 新增资料PUT 完整更新 (会将你设定的覆盖过去,旧有的属性消失)PATCH 局部更新 (除了更新亦可新增属性)DELETE 删除 (不需传入 data)Content-Type: application/x-www-form-urlencoded
为表单栏位必须以 key1=val1&key2=val2 的方式编码jQuery 默认提交方式PHP中以 $_POST['title'] 取得对应值 // 设定表头如此 Content-Type: application/x-www-form-urlencoded;charset=utf-8 // 使用 GET 方法 将参数直接写在待入的 url 上 url/?title=test&name=Tom // 使用 POST 方法 则将资料转成字串传递 const data = 'name=TOM&age=30' xhr.send(data)
呼叫网址範例
GET ~url/users 或 ~url/users/1POST ~url/usersPUT ~url/users/1 (需指定id)PATCH ~url/users/1 (需指定id)DELETE ~url/users/1 (需指定id) // PUT data = { name:'TEST' } name 以外的属性删除 // PATCH data = { name:'TEST' } title 保留,只更新 name
XHR
Get const xhr = new XMLHttpRequest() // true 表 async 非同步(预设) false 表 sync 同步 xhr.open('GET', 'http://localhost:3000/users', true) // 资料传送成功并接收回应后,要作些甚么动作 xhr.onload = function () { if (xhr.status >= 200 && xhr.status < 400) { // 回传值为字串 需要先转换成 JSON 再作运算 console.table(JSON.parse(this.response)) } } // GET 不需要传送资料 xhr.send(null)
POST / PUT / PATCH / DELETE 写法雷同需注意 POST 外,其他皆需指定 idDELETE不需传入资料 const data = { name: 'TEST2', title: 'Title2' } const xhr = new XMLHttpRequest() // PUT、PATCH、DELETE (皆需指定id) ~/users/1 xhr.open('POST', 'http://localhost:3000/users', true) // 设定表头 xhr.setRequestHeader('Content-type', 'application/json ') xhr.onload = function () { if (xhr.status >= 200 && xhr.status < 400) { // 回传刚刚送出的结果 回传值为字串需先转换成 JSON console.table(JSON.parse(this.response)) } } // 需将资料转成 String xhr.send(JSON.stringify(data)) // 如果未转成 String 资料格式不符合时会喷 400 Bad Request xhr.send(data) // Ex: ['test']
Fetch
Fetch 并不会自动传送 Cookie,必须加上表头开启GETcredentials: 'include'
fetch('http://localhost:3000/users/2') .then(res => res.json()) // 先将其转成 JSON 档 .then((data) => { console.table(data) })
GET 使用下面的写法,不可有 body 会喷错stack overflow说明POST / PUT / PATCH / DELETE 写法雷同TypeError: Failed to execute 'fetch' on 'Window': Request with GET/HEAD method cannot have body
// PUT、PATCH、DELETE (皆需指定id) ~/users/1 const postUrl = 'http://localhost:3000/users' const newData = { name: 'PATCH', title: 'PATCH Title' } function postData(url, data = null) { return fetch(url, { method: 'POST', credentials: 'include', // 需传送 Cookie 必须开启 // header外参数 cache mode redirect referrer headers: { 'Content-Type': 'application/json', }, // 注意若 Method 为 GET 不可有 body 会喷错 body: JSON.stringify(data), // 回传仍是 Promise物件 }).then((res) => { // Response objects console.dir(res) // 状态是否为 200-299 if (res.ok) { res.json() } // 即使不设定,他也会自动喷出错误讯息 throw new Error('Network response was not ok.') }) } postData(postUrl, newData).then(res => res.json()) .then((data) => { console.table(data) }) .catch((err) => { console.error(err) })
Response objects
status 回传状态数字 200statusText 回传状态字串 'ok'ok 回传状态是否为 200-299 (Boolean值)Fetch Credentials 参数
Credentials 凭证/Cookie credentials: 'include' (皆发送) credentials: 'same-origin' (同源) credentials: 'omit' (预设值,不发送Cookie)
自订 Request 物件
可自订一些通用的 Header 属性不用每次都重写 // 有 get / set / has / delete 方法可用 const myHeaders = new Headers({ 'Content-Type': 'application/json', }) const myInit = { method: 'GET', headers: myHeaders, mode: 'cors', cache: 'default', } const myRequest = new Request('url', myInit) fetch(myRequest)
常见的 Body
Blob/File 不可变的二进制资料 (图档、音讯)string 文本、阵列、JSONFormData 表单栏位 // blob 图档範例 const myImage = document.querySelector('.TargetImg') fetch('flowers.jpg') .then(res => res.blob()) .then((myBlob) => { let objectURL = URL.createObjectURL(myBlob) myImage.src = objectURL })
FormData 表单栏位
表头必须设定为 multipart/form-data表单 栏位 & 值 建立对应的 键 & 值 let formData = new FormData() let fileField = document.querySelector("input[type='file']") formData.append('username', 'abc123') formData.append('avatar', fileField.files[0]) fetch('https://example.com/profile/avatar', { method: 'PUT', body: formData, }) .then(res => res.json()) .catch(err => console.error('Error:', err)) .then(res => console.log('Success:', res))
Async 小範例
run() async function run() { const getUrl = 'http://localhost:3000/users' const postUrl = 'http://localhost:3000/users' const newData = { name: 'test' } const post = await postData(postUrl, newData) // 回传Promise物件 const res = await fetch(getUrl) const data = await res.json() console.table(data) } function postData(url, data = null) { return fetch(url, { method: 'POST', credentials: 'include', // 需传送 Cookie 必须开启 headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(data), }) }