在我的例子中,我正在尝试扩展TS Window接口以包含polyfill fetch.为什么无所谓.问题是" 我怎么告诉TS这window.fetch是一个有效的函数? "
我在运行TS v.1.5(IIRC)的VS Code,v.0.3.0中这样做.
在我想要使用它的TS类文件中声明接口不起作用:
///<reference path="typings/tsd.d.ts"/>
interface Window {
fetch:(url: string, options?: {}) => Promise<any>
}
...
window.fetch('/blah').then(...); // TS objects that window doesn't have fetch
Run Code Online (Sandbox Code Playgroud)
但是如果我在一个单独的".d.ts"文件中声明这个相同的接口并在我的TS类文件中引用它,那就没关系.
这是"typings/window.extend.d.ts"
///<reference path="es6-promise/es6-promise"/>
interface Window {
fetch:(url: string, options?: {}) => Promise<any>
}
Run Code Online (Sandbox Code Playgroud)
现在我可以在我的TS类文件中使用它:
///<reference path="typings/window.extend.d.ts"/>
...
window.fetch('/blah').then(...); // OK
Run Code Online (Sandbox Code Playgroud)
或者,我可以在我的TS类文件中使用另一个名称编写扩展接口,然后在强制转换中使用它:
interface WindowX extends Window {
fetch:(url: string, options?: {}) => Promise<any>
}
...
(<WindowX> window).fetch('/blah').then(...); // OK
Run Code Online (Sandbox Code Playgroud)
为什么扩展接口工作在"d.ts"而不是就地? …
我正在尝试使用以下代码从开发模式下的 React 应用程序获取无服务器函数。
let response = await fetch(url,
{
method: 'POST',
mode: 'cors',
body: "param=" + paramVar,
})
.then(response => response.json());
Run Code Online (Sandbox Code Playgroud)
后端函数是一个Python Cloud函数,代码如下:
def main(request):
# CORS handling
if request.method == 'OPTIONS':
# Allows GET requests from any origin with the Content-Type
# header and caches preflight response for an 3600s
headers = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST',
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Max-Age': '3600'
}
return ('', 204, headers)
# Set CORS headers for the main request
headers = {
'Content-Type':'application/json', …Run Code Online (Sandbox Code Playgroud) 我在chrome版本52.0.2743.82(64位)上使用fetch.我想获得响应中的所有标题.以下片段仅返回,content-type但如果您查看chrome dev工具,则会显示许多其他响应标头.如何从fetch获取其他标头.
fetch('https://httpbin.org/get')
.then(response => {
const headers = response.headers.entries();
let header = headers.next();
while (!header.done){
console.log(headers.value);
header = header.next();
}
})
Run Code Online (Sandbox Code Playgroud)
我尝试了polyfilling(手动覆盖)github实现.仍然没有运气.
如何将node-fetch包导入到我使用typescript. 我尝试了很多方法......现在我正在:
const fetch = (...args) =>
import("node-fetch").then(({ default: fetch }) => fetch(...args));
Run Code Online (Sandbox Code Playgroud)
但我有两个错误:
Cannot redeclare block-scoped variable 'fetch'.
Run Code Online (Sandbox Code Playgroud)
和
A spread argument must either have a tuple type or be passed to a rest parameter.
Run Code Online (Sandbox Code Playgroud)
当我更改const fetch =为任何其他名称时,例如const fetchIt =它修复了第一个错误,但是......我真的必须更改它吗?如何node-fetch以正常方式导入包,我可以使用fetch()方法?在 React 中我只是做
import fetch from 'node-fetch';
Run Code Online (Sandbox Code Playgroud)
一切都很好......为什么在node项目中如此困难?
在控制台中,运行命令时node --experimental-fetch现在fetch已本机启用(节点版本 >=17.6)。见下文
但是,当我添加打字稿层时,我总是得到error TS2304: Cannot find name 'fetch'.
我该如何解决这个问题?
背景思想:本地使用 fetch 并摆脱node-fetch依赖@types/node-fetch关系
tsconfig.json和一般设置:https ://github.com/nexys-system/server-boilerplate/blob/master/tsconfig.json
也可以看看:
我正在尝试使用 NodeJS 中的本机 fetch 上传文件(在节点 17.5 中添加,请参阅https://nodejs.org/ko/blog/release/v17.5.0/)。
但是,我不断收到以下错误 -
TypeError: fetch failed
at Object.processResponse (node:internal/deps/undici/undici:5536:34)
at node:internal/deps/undici/undici:5858:42
at node:internal/process/task_queues:140:7
at AsyncResource.runInAsyncScope (node:async_hooks:202:9)
at AsyncResource.runMicrotask (node:internal/process/task_queues:137:8)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
cause: TypeError: object2 is not iterable
at action (node:internal/deps/undici/undici:1660:39)
at action.next (<anonymous>)
at Object.pull (node:internal/deps/undici/undici:1708:52)
at ensureIsPromise (node:internal/webstreams/util:172:19)
at readableStreamDefaultControllerCallPullIfNeeded
node:internal/webstreams/readablestream:1884:5)
at node:internal/webstreams/readablestream:1974:7
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
Run Code Online (Sandbox Code Playgroud)
我使用以下代码来创建并提交表单响应 -
TypeError: fetch failed
at Object.processResponse (node:internal/deps/undici/undici:5536:34)
at node:internal/deps/undici/undici:5858:42
at node:internal/process/task_queues:140:7
at AsyncResource.runInAsyncScope (node:async_hooks:202:9)
at AsyncResource.runMicrotask (node:internal/process/task_queues:137:8)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
cause: …Run Code Online (Sandbox Code Playgroud) 我想使用Service Workers来增强现有的网站.特别是,我想通过让Service Workers在实际资源不可用时使用占位符资源响应请求来添加更好的离线支持.这种方法一直有效,但我遇到了一个障碍.站点中有一些地方使用同步 XHR请求来加载某些资源,而我的服务工作者在Chrome中没有收到它们的事件.(请不要建议消除同步XHR请求.这是期望的,但超出范围.)
是否应该让服务工作者能够响应同步XHR请求?我可以想象这实现起来很复杂,并且会理解它是否不受支持.W3C服务工作者规范(工作草案)和WHATWG获取规范(生活标准)之间应该存在"正确"的答案,但我还没有完成对它们的解密.我希望解释规范如何描述是否应该支持这一点,和/或对有关指定或实现此行为的讨论的任何引用.
我有一个ReactJS应用程序在Chrome中按预期工作,但在IE-11中失败.
问题是这样的 - 我们有两个下拉列表,这些列表是在首次加载页面时从其他服务填充的.该应用程序在SSL下运行.当页面通过IE-11加载时,我得到一个IE-11错误问题,其中第一个请求调用被第二个请求调用取消 - 这里描述了错误:
https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/1282036/
所以,我只是向社区询问IE-11是否有解决方法,或者是否依次实现我的代码,如果第一个完成则第二个被调用:
export let getMainData = (dtType, url)=> {
return dispatch=>{
dispatch(sendGet(dtType));
const action = (async(url) => {
const response = await fetch(url);
let data = await response.json();
dispatch(receiveGet(dtType,data));
});
action(url);
};
};
Run Code Online (Sandbox Code Playgroud)
上面的代码是公共代码,React App中的其他人使用它.所以我想的是,如果有一个抽象级别,两个下拉列表可以顺序调用,然后调用上面的下面,也许?
我正在尝试使用 Fetch 将一些数据带入屏幕,但是某些字符显示奇怪的 \xef\xbf\xbd 符号,我认为这与转换特殊字符有关。
\n\n在服务器端调试或在浏览器上调用 servlet 时,问题不会发生,因此我认为问题出在我的 JavaScript 上。请参阅下面的代码:
\n\nvar myHeaders = new Headers();\r\nmyHeaders.append(\'Content-Type\',\'text/plain; charset=UTF-8\');\r\n\r\nfetch(\'getrastreiojadlog?cod=10082551688295\', myHeaders)\r\n .then(function (response) {\r\n return response.text();\r\n })\r\n .then(function (resp) {\r\n console.log(resp);\r\n });Run Code Online (Sandbox Code Playgroud)\r\n我认为这可能是一些细节,但我还没有设法找出发生了什么。欢迎提供任何建议\n谢谢
\n我认为 useeffect 仅在渲染后调用一次,但它被多次执行,而不是按我预期的顺序执行。我希望它在提取过程中 msg 'data loading' ,然后一旦提取完成,呈现标题字段并警告“..Done...”一次,这应该是结束。我在两个点添加了 ALERT 和控制台日志来确定流程,并且警报和控制台日志都以不同的顺序出现不止一次。您能否运行此代码并查看行为。我将第二个参数数组保留为空以使其仅运行一次但无济于事。
其次,请澄清是否反应渲染意味着在屏幕上显示?LOAD 表示什么阶段?什么时候显示完成??
代码如下:
import React, { useEffect, useState } from "react";
//import "./App.css";
function DemoFetchZ() {
let data = { title: "Waiting for Data" };
const [todo, setTodo] = useState(data);
const [isData, setData] = useState(false);
const [isFetching, setFetching] = useState(false);
useEffect(() => { // called after the first render
async function fetchData() {
setFetching(true);
const response = await fetch(
"https://jsonplaceholder.typicode.com/todos/1"
);
console.log("response = ", response);
let data = await response.json();
setTodo(data); …Run Code Online (Sandbox Code Playgroud) fetch-api ×10
javascript ×8
node.js ×3
reactjs ×3
fetch ×2
typescript ×2
cors ×1
html5 ×1
python ×1
rest ×1
use-effect ×1
utf-8 ×1