fetch跨域問題的使用詳解
更新時間:2022年09月15日 10:01:40 作者:喆星高照
這篇文章主要介紹了fetch跨域問題的使用詳解,fetch 的核心主要包括:Request , Response , Header , Body,利用了請求的異步特性 --- 它是基于 promise 的,本文通過實例代碼給大家介紹的非常詳細,需要的朋友可以參考下
一、介紹
fetch 提供了一個獲取資源的接口 (包括跨域)。
fetch 的核心主要包括:Request , Response , Header , Body
利用了請求的異步特性 --- 它是基于 promise 的
1.作用:fetch這個API, 是專門用來發(fā)起Ajax請求的;
fetch('/url').then(data=>{ return data.text(); }).then(ret=>{ //注意,這里才是得到的最終數(shù)據(jù) console.log(ret); });
2.fetch是由原生JS提供的API,專門用來取代XHR這個對象的;
fetch("請求的url地址") .then(response => res.json() ) .then(data => console.log(data)) //注意: 第一個.then 中獲取到的不是最終數(shù)據(jù),而是一個中間的數(shù)據(jù)流對象; // 注意: 第一個 .then 中獲取到的數(shù)據(jù), 是一個 Response 類型對象; // 注意: 第二個 .then 中,獲取到的才是真正的 數(shù)據(jù);
3.發(fā)起Get 請求
// 默認 fetch("url") 的話, 發(fā)起的是 Get 請求 fetch("url") .then(response => { //這個 response 就是 服務器返回的可讀數(shù)據(jù)流, 內部存儲的是二進制數(shù)據(jù) // .json() 的作用,就是 讀取 response 這個二進制數(shù)據(jù)流,并把 讀取到的數(shù) // 據(jù),轉為 JSON 格式的Promise 對象 return response.json() }) .then(data => { //這離 第二個 .then 中拿到的 data, 就是最終的數(shù)據(jù) console.log(data) })
4.發(fā)起Post請求
var sendDate = new URLSearchParams() sendDate.append("name",'ls') sendDate.append("age", 30) fetch("url", { method: "post", body: sendDate //要發(fā)給服務器的數(shù)據(jù) }) .then(response => response.json()) .then(data => console.log(data))
fetch(URL, { method: 'post', body:JSON.stringify(obj), headers:{ 'Content-Type': 'application/json' } }) .then(function (response) { return response.text(); }) .then(function (myJson) { alert(myJson); });
到此這篇關于fetch跨域問題的使用詳解的文章就介紹到這了,更多相關fetch跨域問題內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!