Skip to content

Instantly share code, notes, and snippets.

@xgqfrms-GitHub
Last active September 28, 2020 07:56
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xgqfrms-GitHub/039e67b096ce204379b2aba95fbd494d to your computer and use it in GitHub Desktop.
Save xgqfrms-GitHub/039e67b096ce204379b2aba95fbd494d to your computer and use it in GitHub Desktop.
New Fetch API & `response.json();` & `response.blob();`

Fetch

New Fetch API & response.json(); & response.blob();

https://developer.mozilla.org/zh-CN/docs/Web/API/Body/json

fetch(`https://cdn.xgqfrms.xyz/json/badges.json`)
.then((res) => res.json())
.then((data) => console.log(data));


fetch(`https://cdn.xgqfrms.xyz/json/badges.json`)
.then((res) => res.json())
.then((data) => {
    console.log(data.user);
    console.log(data.courses);
    console.log(data.badges);
});

response.json();

https://developer.mozilla.org/zh-CN/docs/Web/API/Body/json

    
fetch(`https://api.github.com/users/xgqfrms/repos`, {
    method: 'get',
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    }
})
.then(function(response) {
    return response.json();
    // json() ???
})
.then(function(json) {
    console.log('parsed json: ', json);
    console.log('parsed json: ', json[0]);
    console.log('parsed json: ', json[1].name);
})
.catch(function(error) {
    console.log('parsing failed: ', error);
});

https://gist.github.com/xgqfrms-GitHub/2e9c64cdd8e8522cb1d3261d2105b3cb

https://gist.github.com/xgqfrms-GitHub/b44ba9049575654e36e3032c58576931

https://gist.github.com/xgqfrms-GitHub/4afa7b8af41c5060eedd926682627f74

response.blob();

https://developer.mozilla.org/zh-CN/docs/Web/API/Body/blob

let myImage = document.querySelector('img');

fetch('flowers.jpg')
.then(function(response) {
    return response.blob();
})
.then(function(myBlob) {
    let objectURL = URL.createObjectURL(myBlob);
    myImage.src = objectURL;
});

Docs

https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API/Using_Fetch

https://developer.mozilla.org/zh-CN/docs/Web/API/Body/blob

Headers()

let myHeaders = new Headers(),
    myInit = { 
        method: 'GET',
        headers: myHeaders,
        mode: 'cors',
        cache: 'default' 
    };

fetch('flowers.jpg',myInit)
.then((response) => response.blob())
.then((myBlob) => {
    let objectURL = URL.createObjectURL(myBlob);
    myImage.src = objectURL;
});

response.ok

fetch(`https://cdn.xgqfrms.xyz/logo/icon.png`)
.then((response) => {
    if(response.ok) {
        ((response) => response.blob())
       .then((myBlob) => {
            let objectURL = URL.createObjectURL(myBlob);
            myImage.src = objectURL;
        });
    }else {
        console.log('Network response was not ok.');
    }
})
.catch((error) => {
    let emsg = `
        There has been a problem with your fetch operation: \n
        ${error.message}!
    `;
    console.log(`emsg = `, emsg);
    console.log(`emsg = \n`, this.fetch);
    console.log(`emsg = \t`, this.location.href);
});
let myHeaders = new Headers();
let myInit = { 
    method: 'GET',
    headers: myHeaders,
    mode: 'cors',
    cache: 'default'
};
let myRequest = new Request('flowers.jpg', myInit);

fetch(myRequest)
.then((response) => response.blob())
.then((myBlob) => {
    let objectURL = URL.createObjectURL(myBlob);
    myImage.src = objectURL;
});

Body

Body 类定义了以下方法 (这些方法都被 Request 和 Response所实现)以获取body内容.
这些方法都会返回一个被解析后的promise对象和数据.

arrayBuffer()
blob()
json()
text()
formData()

Response.ok

https://developer.mozilla.org/zh-CN/docs/Web/API/Response/ok

https://developer.mozilla.org/zh-CN/docs/Web/API/Response/status

Response 接口的status 只读属性包含响应的状态代码(例如,成功为200)。

https://developer.mozilla.org/zh-CN/docs/Web/API/Response/statusText

Response 接口的 statusText只读属性包含与状态代码相对应的状态消息(例如,对于200可以确定)。

https://developer.mozilla.org/zh-CN/docs/Web/API/Body/json

Response

https://developer.mozilla.org/zh-CN/docs/Web/API/Response/Response

Response() 构造函数创建了一个新的 Response 对象.

Fetch & JSON & Body.json()

https://developer.mozilla.org/zh-CN/docs/Web/API/Body/json

Body mixin 的 json() 方法使用一个 Response 流,并将其读取完成。 它返回一个 promise ,解析结果是将文本体解析为 JSON。

https://developer.mozilla.org/zh-CN/docs/Web/API/Body/blob

Body mixin的 blob() 方法使用一个 Response 流,并将其读取完成。 它返回一个使用一个 Blob解决{的promise。

https://developer.mozilla.org/zh-CN/docs/Web/API/GlobalFetch/fetch

https://developer.mozilla.org/zh-CN/docs/Web/API/Body

Fetch API 中的 Body mixin 代表 代表响应/请求的正文,允许你声明其内容类型是什么以及应该如何处理。

正文由Request 和Response实现 --- 这为这些对象提供了一个相关联的主体(字节流), 一个已使用的标志(最初未设置) 和一个MIME类型(最初为空字节序列)


Blogs

https://jakearchibald.com/2015/thats-so-fetch/

https://davidwalsh.name/fetch

https://developers.google.com/web/updates/2015/03/introduction-to-fetch

https://scotch.io/tutorials/how-to-use-the-javascript-fetch-api-to-get-data


API

https://github.github.io/fetch/


stackoverflow

https://stackoverflow.com/questions/32721850/why-the-response-object-from-javascript-fetch-api-is-a-promise

fetch-post-json-data

https://stackoverflow.com/questions/29775797/fetch-post-json-data

Promises

https://www.promisejs.org/

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise#参见

@xgqfrms-GitHub
Copy link
Author

@xgqfrms-GitHub
Copy link
Author

@xgqfrms-GitHub
Copy link
Author

xgqfrms-GitHub commented Jun 10, 2017

JSON.parse(res) & res.json()

fetch(`https://cdn.xgqfrms.xyz/json/badges.json`)
.then((res) => res.json())
.then((data) => console.log(data));


fetch(`https://cdn.xgqfrms.xyz/json/badges.json`)
.then((res) => res.json())
.then((data) => {
    console.log(data.user);
    console.log(data.courses);
    console.log(data.badges);
});


fetch(`https://cdn.xgqfrms.xyz/json/badges.json`)
.then((res) => res.json())
.then((data) => console.log(data));


fetch(`https://cdn.xgqfrms.xyz/json/badges.json`)
.then((res) => JSON.parse(res))
.then((data) => {
    console.log(data.user);
    console.log(data.courses);
    console.log(data.badges);
});

@xgqfrms-GitHub
Copy link
Author

fetch-object

@xgqfrms-GitHub
Copy link
Author

fetch-json parse res -error

@xgqfrms-GitHub
Copy link
Author

let username = `xgqfrms-GitHub`;
    repo = `Node-CLI-Tools/commits`;

fetch(`https://api.github.com/users/${username}/${repo}`,{
    data: {
        client_id: '08ecc2f68d922f18800e',
        client_secret: '5846d428b5340812b76c9637eceaee979340b922'
    }
})
.then((response) => response.json())
.then((json)=> {
    console.log(`json = ${json}`);
    return repos = json;
})
.then((repos)=>{
    console.log(`repos = ${repos}`);
    console.log(`repos = ${repos.length}`);
    console.log(`repos$ 0  = ${repos[0]}`);
    console.log(`repos$ 1  = ${repos[1]}`);
    for (let i = 0; i < repos.length; i++) {
        console.log(`repos${i}  = ${repos[i]}`);
    }
});




let username = `xgqfrms-GitHub`;

fetch(`https://api.github.com/users/${username}/repos`,{
    data: {
        client_id: '08ecc2f68d922f18800e',
        client_secret: '5846d428b5340812b76c9637eceaee979340b922'
    }
})
.then((response) => response.json())
.then((json)=> {
    console.log(`json = ${json}`);
    return repos = json;
})
.then((repos)=>{
    console.log(`repos = ${repos}`);
    console.log(`repos = ${repos.length}`);
    console.log(`repos$ 0  = ${repos[0]}`);
    console.log(`repos$ 1  = ${repos[1]}`);
    for (let i = 0; i < repos.length; i++) {
        console.log(`repos${i}  = ${repos[i]}`);
    }
});

@xgqfrms007
Copy link

@xgqfrms
Copy link

xgqfrms commented Sep 28, 2020

fetch api

import 'whatwg-fetch';
// fetch polyfill

const url = <code>https://abc.xgqfrms.xyz/some-url</code>;

const headers = new Headers({
    'Content-Type': 'text/plain',
    'X-My-Custom-Header': 'CustomValue'
});

const datas = JSON.stringify(
    {
        user: "username",
        pwd: "password"
    }
);

const method = <code>POST</code>;

const request = new Request(url, {
    headers: headers,
    method: 'POST', 
    mode: 'cors', 
    redirect: 'follow',
    body: datas
});

fetch(
    request
).then(
    (response) => response.json()
).catch(
    (err) => {
        console.log(<code>err</code>, err);
        throw new Error("Whoops, An Error occurred!");
    }
);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment