xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

Fetch API & HTTP Response opaque All In One

Fetch API & HTTP Response opaque All In One

error

Promise {<rejected>: SyntaxError: Unexpected end of input at

A no-cors request makes the response type opaque.
Opaque means your frontend JavaScript code can’t see the response body or headers. ❌

  const promise = await fetch(url, {
    // method: 'GET', // *GET, POST, PUT, DELETE, etc.
    // mode: 'cors', // no-cors, *cors, same-origin
    // cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
    // credentials: 'same-origin',
    // credentials: 'include',
    method: 'GET',
    // mode: 'no-cors',
    // ❌  A no-cors request makes the response type opaque. Opaque means your frontend JavaScript code can’t see the response body or headers.
    // responseType: 'arraybuffer',
    // responseType: 'blob',
    headers: {
      // 'Accept': type,
      'Content-Type': type,
      // 'Content-Type': 'application/octet-stream',
      // 'Accept': 'video/mp4',
      // 'Accept': 'application/json',
      // 'Content-Type': 'application/json;charset=utf-8'
      // 'Content-Type': 'application/json',
      // 'Content-Type': 'application/x-www-form-urlencoded',
      // ...headers,
    },
  }).then(res => {
    if(type.includes('json')) {
      const json = res.json();
      console.log('json =', json);
      return json;
    } else {
      const buffer = res.arrayBuffer();
      console.log('buffer =', buffer);
      return buffer;
    }
  }).then(data => {
    console.log('data =', data);
    const blob = new Blob(
      [data],
      {'type' : type},
    );
    const urlBlob = URL.createObjectURL(blob);
    dom.src = urlBlob;
    link.href = urlBlob;
    link.innerText = urlBlob;
  }).catch(err => {}).finally(() => {});

https://stackoverflow.com/questions/43317967/handle-response-syntaxerror-unexpected-end-of-input-when-using-mode-no-cors

HTTP Response & type: 'opaque',

// res = Response {type: 'opaque', url: '', redirected: false, status: 0, ok: false, …}body: (...)bodyUsed: falseheaders: Headers {}ok: falseredirected: falsestatus: 0statusText: ""type: "opaque"url: ""[[Prototype]]: Response
fetch.js:48 buffer = Promise {<fulfilled>: ArrayBuffer(0)}

ReadableStream

type: "basic"
url: "https://cdn.xgqfrms.xyz/HTML5/Blob/2022-04-07-sh.mp4

// fetch.response = Response
fetch.response = Response {type: 'basic', url: 'https://cdn.xgqfrms.xyz/HTML5/Blob/2022-04-07-sh.mp4', redirected: false, status: 200, ok: true, …}body: ReadableStreamlocked: true[[Prototype]]: ReadableStreamcancel: ƒ cancel()getReader: ƒ getReader()length: 0name: "getReader"arguments: (...)caller: (...)[[Prototype]]: ƒ ()[[Scopes]]: Scopes[0]locked: truepipeThrough: ƒ pipeThrough()pipeTo: ƒ pipeTo()tee: ƒ tee()constructor: ƒ ReadableStream()Symbol(Symbol.toStringTag): "ReadableStream"get locked: ƒ locked()[[Prototype]]: ObjectbodyUsed: trueheaders: Headers {}ok: trueredirected: falsestatus: 200statusText: ""type: "basic"url: "https://cdn.xgqfrms.xyz/HTML5/Blob/2022-04-07-sh.mp4"[[Prototype]]: ResponsearrayBuffer: ƒ arrayBuffer()blob: ƒ blob()body: ReadableStreambodyUsed: (...)clone: ƒ clone()formData: ƒ formData()headers: (...)json: ƒ json()ok: (...)redirected: (...)status: (...)statusText: ""text: ƒ text()type: "basic"url: "https://cdn.xgqfrms.xyz/HTML5/Blob/2022-04-07-sh.mp4"constructor: ƒ Response()Symbol(Symbol.toStringTag): "Response"get body: ƒ body()get bodyUsed: ƒ bodyUsed()get headers: ƒ headers()get ok: ƒ ok()get redirected: ƒ redirected()get status: ƒ status()get statusText: ƒ statusText()get type: ƒ type()get url: ƒ url()[[Prototype]]: Object

demos

<iframe src="https://cdn.xgqfrms.xyz/HTML5/Blob/fetch/index.html" width="100%" height="500"></iframe>

https://cdn.xgqfrms.xyz/HTML5/Blob/fetch/index.html

preview codepen (click run pen)

https://codepen.io/xgqfrms/embed/preview/XWVYQPb

<iframe height="558.0556640625" style="width: 100%;" scrolling="no" title="Fetch API &amp; Blob File Download &amp; HTML5 Download" src="https://codepen.io/xgqfrms/embed/XWVYQPb?default-tab=result&theme-id=dark" frameborder="no" loading="lazy" allowtransparency="true" allowfullscreen="true">
  See the Pen <a href="https://codepen.io/xgqfrms/pen/XWVYQPb">
  Fetch API &amp; Blob File Download &amp; HTML5 Download</a> by xgqfrms (<a href="https://codepen.io/xgqfrms">@xgqfrms</a>)
  on <a href="https://codepen.io">CodePen</a>.
</iframe>

https://codepen.io/xgqfrms/embed/XWVYQPb

(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!

credentials

fetch POST cookies & credentials

fetch(`http://localhost:3000/api/post`, {
    body: JSON.stringify({key: "value"}),
    // cache: "no-cache",
    headers: {
        "Content-Type": "application/json",
    },
    method: "POST",
    // cookies
    credentials: 'include',
    // credentials: 'same-origin',
    // credentials: 'omit',
    // mode: "no-cors",
    mode: "cors",
})
.then(res => console.log(`res =`, res))
.catch(err => console.error(`error =`, err));

  1. same-origin
    Send user credentials (cookies, basic http auth, etc..) if the URL is on the same origin as the calling script.
    This is the default value.

  2. include
    Always send user credentials (cookies, basic http auth, etc..), even for cross-origin calls.

  3. omit
    Never send or receive cookies.

https://developer.mozilla.org/en-US/docs/Web/API/Request/credentials

const xhr = new XMLHttpRequest();
xhr.open("GET", "http://example.com/", true);
xhr.withCredentials = true;
xhr.send(null);

https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials

https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie

https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies

refs

https://github.com/xgqfrms/learning/issues/24



©xgqfrms 2012-2021

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2022-04-12 00:46  xgqfrms  阅读(1143)  评论(2编辑  收藏  举报