这就是我的意思。
如果浏览器本机支持fetch api(例如,Chrome),则它使用本机浏览器Promise。
如果我使用另一个 Promise 库(例如bluebird), nativefetch仍然没有使用它——而是使用 nativePromise实现。
有没有办法覆盖它?
问题示例:
window.Promise = function () { return null; };
fetch('/api')
.then(function (res) {
console.log('fetch result!', res); // still works because it uses native Promise
});
Run Code Online (Sandbox Code Playgroud)
为什么我需要那个,你可能想知道?我希望利用全球排斥事件,其bluebird库支持和原生的承诺不具备的。
我正在通过 javascript fetch 调用身份验证服务来获取访问令牌。该服务是一个简单的 RESTful 调用。我可以看到使用 fiddler 调用成功(带有 200 响应和 json 数据)。然而,fetch 响应似乎永远不会被调用。下面是一个片段:
const AUTHBODY = `grant_type=password&username=${username}&password=${password}&scope=roles offline_access profile`
const AUTHHEADER = new Headers({'Content-Type': 'application/x-www-form-urlencoded'})
const CONFIG = {
method: 'POST',
headers: AUTHHEADER,
body: AUTHBODY
}
fetch('http://localhost:23461/connect/token', CONFIG).then(function(response) {
console.log('response = ' + response)
return response.json()
}).then(function(json) {
console.log('json data = ' + json)
return json
}).catch(function(error) {
console.log('error = ' + error)
})
Run Code Online (Sandbox Code Playgroud)
当执行上面的 fetch 时,console.logs 都没有被执行......似乎只是挂起。但提琴手另有说法。有任何想法吗?
我们可以修改XMLHttpRequest.prototype.open劫持之前的所有Ajax请求。切换到新浏览器的 fetch API 有什么等价的?
const originalRequestOpen = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function() {
this.addEventListener('load', function() {
// do something
});
originalRequestOpen.apply(this, arguments);
};
Run Code Online (Sandbox Code Playgroud) 有一个Web应用程序发出请求(我们称它为/api/item)。该请求返回一个带有称为的字段的json主体,该字段itemData通常对用户隐藏,但我想显示该字段。
那么,如何使用户脚本在以下位置监听请求/api/item并显示itemData字段?
作为参考,webapp发出请求的方式为:
return Promise.resolve(new Request(e,r)).then(sendCookies).then(addLangParam).then(addCacheParam).then(addXsrfKey).then(checkZeroRating).then(function(e) {
return fetch(e)
}).then(checkStatus).then(checkApiVersionMismatch).then(checkApiResponse)
Run Code Online (Sandbox Code Playgroud)
大多数都无关紧要,但重要的部分是Request(我认为)。
我正在尝试使用Fetch API来处理XML数据的POST,以避免XmlHttpRequest的跨源问题.我面临的问题是尽管将我的Content-Type设置为'text/xml'(在这种情况下是唯一支持的内容类型标头),我的请求的内容类型被重置为text/plain,导致HTTP状态为415来自所请求的内容.
这是我的获取功能:
function doFetch(Content)
{
return fetch(
URL, { method: 'POST',
mode: 'no-cors',
headers: new Headers(
{'Content-Type': 'text/xml; charset=utf-8',
'Accept': '*/*',
'Accept-Language': 'en-GB',
'Accept-Encoding': 'gzip, deflate',
'Connection': 'Keep-alive',
'Content-Length': Content.length
}),
body: Content
});
}
Run Code Online (Sandbox Code Playgroud)
内容是一串XML数据.
这是实际使用的标头:
Content-Length:1537
content-type:text/plain;charset=UTF-8
Run Code Online (Sandbox Code Playgroud)
只是想知道我正在尝试做什么是可能的,如果这是我做错了什么?(我对网络开发有点新意).
谢谢!
在后台运行并由push事件触发的服务工作者的上下文中,Chrome (Android) 未启动,我尝试使用fetchAPI发送带有 TLS 客户端证书的 HTTP 请求。
当 Chrome 启动时请求成功,TLS 证书已经发送到服务器。但是在上述情况下请求失败并出现以下错误:"failed to load resource: net::ERR_SSL_CLIENT_AUTH_CERT_NEEDED"。
我试过使用这些Request选项{credentials: 'include'},{ credentials: 'origin' }但没有成功。
使用带有 TLS 客户端证书的 fetch API 的正确方法是什么?
javascript android google-chrome client-certificates fetch-api
我正努力node-fetch在我的打字稿项目中工作:
import * as fetch from 'node-fetch';
import * as assert from 'assert';
export class DatabaseConfigurator {
private url: string;
getNode (): Promise<string> {
return fetch(`${this.url}/_membership`).then((response: fetch.Response) => {
return response.json();
}).then((res: any) => {
assert.equal(res.all_nodes.length, 1);
return res.all_nodes[0];
});
}
}
Run Code Online (Sandbox Code Playgroud)
我得到:
Cannot invoke an expression whose type lacks a call signature. Type 'typeof "/home/vinz243/compactd/node_modules/@types/node-fetch/index"' has no compatible call signatures.
Run Code Online (Sandbox Code Playgroud)
当我安装的定义似乎ok(node_modules/@types/node-fetch/index.d.ts):
...
export default function fetch(url: string | Request, init?: RequestInit): Promise<Response>;
Run Code Online (Sandbox Code Playgroud)
我的 tsconfig.json
{ …Run Code Online (Sandbox Code Playgroud) 我正在使用 Aurelia Fetch Client 向 Web API 端点发送文件上传请求。但是 IFormFile 是空的所有磁贴。我的代码如下。
const formData = new FormData();
formData.append("files", account.statement);
const response = await this.http.fetch(url, { method: "POST", body: formData
});
Run Code Online (Sandbox Code Playgroud)
[HttpPost]
public IActionResult Save ()
{
var files = Request.Form.Files;
}
Run Code Online (Sandbox Code Playgroud)
文件始终为空。我已经关注了这篇文章,并按照上面提到的做了。但仍然无法弄清楚什么是错的。
我在玩fetch,并且注意到当我获取的资源不存在(又名404)时,只有Chrome显示错误:

Edge和Firefox都不这样做,并且使用fetch的404错误似乎也不会触发NetworkError使我的catch错误处理程序得到通知。我应该怎么做才能避免Chrome中出现此错误?
如果您需要它,我的完整代码如下所示:
fetch("https://www.kirupa.com/book/images/learning_react2.gif", {
method: "head",
mode: "no-cors"
})
.then(function(response) {
if (response.status == 200) {
console.log("file exists!");
} else {
console.log("file doesn't exist!");
}
return response.text();
})
.catch(function(error) {
console.log("Error ", error);
});
Run Code Online (Sandbox Code Playgroud)
谢谢,基鲁帕
使用Fetch API时,我试图捕获与同一原始策略相关的许多错误,但未成功:
window.onerror = (message, file, line, col, error) => console.log(error)
window.addEventListener('error', (error) => console.log(error))
try {
fetch('https://www.bitstamp.net/api/ticker/').catch(e => {
console.log('Caugth error:')
console.log(e)
console.log(JSON.stringify(e))
})
}
catch (e) {
console.log('try-catch')
console.log(e)
}
Run Code Online (Sandbox Code Playgroud)
我要捕获的错误仅出现在Web控制台中:
在此处查看代码示例:https : //github.com/nyg/fetch-error-test
如何捕获这些错误以提供屏幕消息?
编辑:实际执行获取的catch块。
window.onerror = (message, file, line, col, error) => console.log(error)
window.addEventListener('error', (error) => console.log(error))
try {
fetch('https://www.bitstamp.net/api/ticker/').catch(e => {
console.log('Caugth error:')
console.log(e)
console.log(JSON.stringify(e))
})
}
catch (e) {
console.log('try-catch')
console.log(e)
}
Run Code Online (Sandbox Code Playgroud)
fetch('https://www.bitstamp.net/api/ticker/')
.then(response => response.text())
.then(pre)
.catch(e => {
pre(`Caugth error: …Run Code Online (Sandbox Code Playgroud)fetch-api ×10
javascript ×8
cors ×2
android ×1
es6-promise ×1
greasemonkey ×1
iformfile ×1
node.js ×1
onerror ×1
post ×1
tampermonkey ×1
typescript ×1
userscripts ×1
xml ×1