關於 Fetch API 的注意事項

fetch(url, {
    // 'GET', 'POST', 'PUT', 'DELETE'等
    method: 'GET', 
})

關於 GET 參數

發送GET請求時的query參數不能放到對象中(如:{a:1, b:2}) 必須在 url 字符串中:json

const url = 'http://api.example.com/search?a=1&b=2'

可經過以下函數處理urlsegmentfault

function makeURL(url, params = {}) {
    let _URL = new URL(url, window.location.origin);
    Object.keys(params).forEach(key => _URL.searchParams.append(key, params[key]));
    return _URL
}
const url = makeURL('http://api.example.com/search',{
    a: 1,
    b: 2,
})

而後發起請求:api

fetch(url, {
    method: 'GET'
})

關於 POST 請求體 body

如需經過POST請求的發送json,須要作字符串化處理:cookie

fetch(url, {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
    }
    body: JSON.stringify({a: 1, b: 2})
})

關於 cookies

Fetch 發送請求默認不攜帶 cookies,如需攜帶,須要添加credentials: 'include' 參數:app

fetch(url,{
    method: 'GET', // 'POST'等
    credentials: 'include',
})

關於 Headers

定義headers函數

const headers = {
    "Content-Type": "application/x-www-form-urlencoded"
    "Authorization": "Token uynn887989afs989s8df9afa08&^&huh"
}

fetch

const headers = new Headers({
    "Content-Type": "application/x-www-form-urlencoded"
    "Authorization": "Token uynn887989afs989s8df9afa08&^&huh"
})

發送請求:url

fetch(url, {
  method: "POST",
  headers: headers,
}

自定義的 headers中的鍵會通過 Headers 對象包裝,會自動轉換爲小寫。code

// Create a test Headers object
var myHeaders = new Headers();
myHeaders.append('Content-Type', 'text/xml');
myHeaders.append('Vary', 'Accept-Language');

// Display the key/value pairs
for (var [key,value] of myHeaders.entries()) {
    console.log(`${key}: ${value}`);
}

輸出爲:orm

content-type: text/xml
VM141:8 vary: Accept-Language

所以當咱們發送 Authorization 令牌時,在服務端接收到的是 authorization,若是仍用 Authorization 處理,將發生錯誤。

文件上傳失敗解決

刪除你的自定義Content-Type請求頭設置

參見:fetch實(cai)踐(keng)補充篇,文件上傳Content-type multipart/form-data怎麼設置

相關文章
相關標籤/搜索