alc*_*cia 5 javascript safari fetch
上次更新 Safari 浏览器(更新至 11.1)后,我注意到我的获取代码停止工作。
代码:
const options = {
method: 'POST',
credentials: 'include',
body: '{"id":"xxx","note":"yyy"}',
headers: {}
};
options.headers = new window.Headers();
options.headers.append('Content-Type', 'application/json; charset=utf-8');
function getRequest() {
return new window.Request('https://jsonplaceholder.typicode.com/posts', options);
}
const newRe = getRequest();
console.log(newRe);
fetch(newRe)
.then((response) => {
return response.json();
})
.then((jsonObject) => {
console.log(jsonObject)
document.write(`ID ${jsonObject.id} was created!`);
})
.catch((error) => {
document.write(error);
});
Run Code Online (Sandbox Code Playgroud)
Codepen 上:https: //codepen.io/anon/pen/BrXoqG
在 Safari 11.1 上返回错误:“NotSupportedError:不支持 ReadableStream 上传”。但是,如果您删除 行console.log(newRe),一切都会正常工作。
为什么?
Safari 似乎不支持使用Request具有POST方法的对象进行 fetch ;可能是因为现在当你构造一个Request对象时,主体被包装在ReadableStream.
您可以将Request对象转换为参数元组:
const body = await request.clone().text();
const {cache, credentials, headers, integrity, mode, redirect, referrer} = request;
const init = {body, cache, credentials, headers, integrity, mode, redirect, referrer};
fetch(request.url, init);
Run Code Online (Sandbox Code Playgroud)