请不要标记为重复。这与此处的其他类似问题并不完全相同。它更具体且完全可重现。
yarn && yarn devlocalhost:3000(F12)->Applications->Service Workers 并确保已安装 Service Worker。或者,如果您想手动执行此操作,请按照以下说明操作:
yarn create-next-app app_namecd app_name && yarnservice-worker.js并粘贴以下代码:addEventListener("install", (event) => {
self.skipWaiting();
console.log("Service worker installed!");
});
self.addEventListener("fetch", (event) => {
event.respondWith(
(async function () {
const promiseChain = fetch(event.request.clone()); // clone makes no difference
event.waitUntil(promiseChain); // makes no difference
return promiseChain;
})()
);
});
Run Code Online (Sandbox Code Playgroud)
pages/index.js并在下面import Head from "next/head";粘贴以下代码:if (typeof window !== "undefined" && …Run Code Online (Sandbox Code Playgroud) 我有一个fetch POST正在发送一个大的 JSON 对象:
const body = JSON.stringify(largeItem); // 80MB
const request = new Request(uri, {
mode: 'cors',
method: 'POST',
headers: new Headers({ 'Content-Type': 'application/json' }),
credentials: 'same-origin',
body
});
const response = await fetch(request);
Run Code Online (Sandbox Code Playgroud)
这会导致错误:
source-file.ts:72 Uncaught (in promise) TypeError: Failed to fetch
当我在开发工具中查看此请求时,它看起来不完整 - 没有请求正文,并且大多数请求标头都丢失了。此外,它的错误没有状态代码,而是状态为:
(failed) net::ERR_CONNECTION_RESET
使用相同凭据对同一资源进行许多其他GET请求都可以正常工作。POST此代码适用于较小的body.
如何使用POST大型(本例中为 80MB)JSON 正文发出请求?
我正在尝试使用 Javascript 获取方法,但是,它似乎不能异步工作。
这是我的代码:
fetch(`${global.URL}${url}`, requestConfig)
.then(res => res.json())
.then(res => {
console.log('response', res);
return res;
})
.catch(error => {
console.log('error: ', error)
})
Run Code Online (Sandbox Code Playgroud)
我在 70% 的情况下收到以下错误,然后在另外 30% 的情况下收到有效响应,当我保存文件并重新渲染时,它有时会起作用。
error: SyntaxError: Unexpected token T in JSON at position 0
at parse (<anonymous>)
at tryCallOne (core.js:37)
at core.js:123
at JSTimers.js:277
at _callTimer (JSTimers.js:135)
at _callImmediatesPass (JSTimers.js:183)
at Object.callImmediates (JSTimers.js:446)
at MessageQueue.__callImmediates (MessageQueue.js:396)
at MessageQueue.js:144
at MessageQueue.__guard (MessageQueue.js:373)
Run Code Online (Sandbox Code Playgroud)
我尝试在 async/await 函数内部调用它,但没有帮助。
编辑1:
这就是我提出要求的方式
const authenticityToken = global.TOKEN
const query = (url, config) …Run Code Online (Sandbox Code Playgroud) 我在 React js 中有一个提取请求,它调用 API(Node js 后端服务器)。对于通过 Google Chrome 发出的任何耗时超过 2 分钟的请求,获取请求都会引发错误:
“获取失败”。
如果我传递的参数较少(即请求哪个服务器花费的时间少于 2 分钟),则它可以正常工作。
下面是我的代码。
fetch(url , requestOptions)
.then(response => response.blob())
.then(blob => {
const newBlob = new Blob( [blob], {type: 'application/zip'});
const downloadUrl = URL.createObjectURL(newBlob)
let a = document.createElement("a");
a.href = downloadUrl;
a.download = "reports";
document.body.appendChild(a);
a.click();
alert(this.state.selectedReport + "Reports Downloaded Successfully")
})
.catch((error) => {
alert("Error in downloading report " + error)
})
Run Code Online (Sandbox Code Playgroud)
通过网上浏览,发现fetch请求中没有超时参数。
我尝试使用等待和异步,但它没有成功,并且还从下面的链接中得到答案。
我想获取后端服务器花费超过2分钟的数据。谁可以帮我这个事?
我正在尝试让 Elasticsearch 服务器运行,但无法成功。
我在 localhost:9200 上运行 Elasticsearch,在 localhost:3310 上运行一个 Express 服务器,我在其中运行 node.js 和我的代码(html 和 js)。
我正在使用 fetch 向 elasticsearch 发出 http 请求以检索数据。如果我使用带有 URL 的精简搜索,例如:
http://localhost:9200/movies2/_search?q=fields.title:Lord
Run Code Online (Sandbox Code Playgroud)
它有效,但是当我尝试使用 fetch 发出请求时,例如:
const source= "http://localhost:9200/movies2/_search?"
var myInit = { method: 'POST',
mode: 'cors',
cache: 'default' ,
header : {
"Access-Control-Allow-Origin" : "*",
"Content-Type": "application/json"
},
body : JSON.stringify({
"query" : {
"match" : {[searchDSL]: x}
}
})
};
let reqLite = await fetch(source, myInit)
Run Code Online (Sandbox Code Playgroud)
事实并非如此。我有这个错误:
错误:“不支持内容类型标头 [text/plain;charset=UTF-8]”
我不明白为什么我会收到这条消息。我根据我的请求、标头以及 elasticsearch .yml 文件授权了 CORS:
http.cors.enabled: true …Run Code Online (Sandbox Code Playgroud) 我在 NEXT JS 中使用 getServerSideProps 函数进行 fetch 时遇到问题。当我开始使用这个框架时,我可能做得不好。访问外部 API 的所有凭据都是正确的。当我在 React 中使用相同的参数进行获取时,它会为我带来信息,但是使用 Next JS 它会返回 400 - 错误请求。
\n我将所有参数放在下面同一个块代码中,以便于理解。我使用像“”这样的凭据参数来保护隐私。他们是正确的,没有任何问题。
\n注意:我相信我一定以错误的方式使用了 getServerSideProps 函数。我不知道除了编写函数之外是否还需要对 Next JS 进行任何配置。换句话说,这里显示的是我到目前为止实际写的内容。该程序直接从index.js 调用。
\n这是文件夹结构:
\n\nListOrders 是我渲染页面的地方。它从我执行提取操作的 getServerSideProps 函数接收 {orders} 作为 props。
\nconst ListOrders = ({ orders }) => {\n // Render orders through server side rendering (SSR)\n return (\n <div>\n {/* If orders is an object than map over it to render the page, otherwise orders is an error message …Run Code Online (Sandbox Code Playgroud) 我在 Node 服务器上有 API,在调用时返回如下 JSON:
{"result":[{"ProductID":1,"ProductName":"iPhone10","ProductDescription":"Latest smartphone from Apple","ProductQuantity":100}]}
Run Code Online (Sandbox Code Playgroud)
我正在尝试使用 fetch API 和 React 向用户显示所有这些信息,但无论我的调用返回什么undefined。这是我的反应代码:
const [products, setProducts] = useState({})
async function getProducts() {
await fetch(`http://127.0.0.1:5000/listProducts`)
.then(response => response.json())
.then(response=>{
setProducts({products:response.result})
console.log(response.result);
products.map(products =>
<h1>{products.ProductName}</h1>
<h1>{products.ProductDescription}</h1>
)
})
.catch(err=>console.error(err))
}
Run Code Online (Sandbox Code Playgroud)
页面加载时,函数 getProducts() 被调用一次。我做错了什么?提前致谢。
对于我的小型 Javascript 应用程序,我使用CGI编写了服务器端 API 函数。
我让它变得非常简单,完整的示例脚本如下所示:
#!/usr/bin/env perl
use strict; use warnings; use 5.014;
use CGI;
use JSON;
use Data::Dumper;
my $q = new CGI;
my %p = $q->Vars;
_api_response();
sub _api_response {
my ( $error ) = @_;
my $res;
my $status = 200;
my $type = 'application/json';
my $charset = 'utf-8';
if ( $error ) {
$status = 500;
$res->{data} = {
status => 500,
};
$res->{error} = {
error => 'failure',
message => $error,
detail => …Run Code Online (Sandbox Code Playgroud) 是的,我有可怕的 CORS 问题(或者,至少看起来是这样)……我已经搜索并尝试了一些解决方案,但无济于事……
我使用 firebase 模拟器并在本地运行我的函数没有任何问题,但是当我部署该函数并尝试在本地主机客户端应用程序上使用 fetch() 发送 POST 请求时,我收到以下 CORs 浏览器控制台错误(它赢得了甚至无法访问服务器日志):
Access to fetch at 'https://us-central1-XXXX.cloudfunctions.net/deleteAsset' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
The FetchEvent for "https://us-central1-XXXXX.cloudfunctions.net/deleteAsset" resulted in a network error response: the promise was rejected.
Promise.then (async) …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用此端点将视频上传到 Tiktok:
https://open-api.tiktok.com/share/video/upload/
遵循官方文档: https://developers.tiktok.com/doc/web-video-kit-with-web
(成功通过 Tiktok 进行身份验证并使用 Login Kit API 获取访问令牌后)。我收到的响应表明成功(error_code=0 和非空 share_id),但是没有上传任何内容,并且我的 Tiktok 应用程序的回调网址似乎没有被任何状态更新触发。
我尝试过从几个不同的环境访问 API - Node.js 运行时(使用 Axios)、来自 2 台不同机器的 cURL 请求(都得到上述结果)以及使用 Fetch 从我的前端代码(这个让我CORS 错误)。下面的代码片段。
我将不胜感激任何帮助,因为我不知道接下来要尝试什么。此外,如果除了我链接的文档或在线资源之外还有任何其他文档或在线资源可能会有所帮助,那么任何此类链接都会很棒。
注意:我确保我的测试视频满足文档中提到的限制。
我的 Node.js 代码:
const url = `https://open-api.tiktok.com/share/video/upload?open_id=${openId}&access_token=${accessToken}`;
const data = new FormData();
data.append('video', fs.createReadStream(path.join(os.tmpdir(), 'test.mp4')));
await axios.post(url, data, {
headers: data.getHeaders()
});
Run Code Online (Sandbox Code Playgroud)
卷曲请求:
curl --location --request POST 'https://open-api.tiktok.com/share/video/upload?open_id=<open_id>&access_token=<access_token>' --form 'video=@"/path/to/video.mp4"'
Run Code Online (Sandbox Code Playgroud)
响应负载(对于 cURL 和 Node.JS 请求):
{"data":{"err_code":0,"error_code":0,"share_id":"video.7031619168818448385.CGdXCmaC"},"extra":{"error_detail":"","logid":"2021111721133201024513311411A971D3"}}
Run Code Online (Sandbox Code Playgroud)
前端代码(获取,在 Location 标头中使用相同的 Tiktok URL(/share/video/upload...)获取 307 响应 - 导致 CORS 错误):
const formData …Run Code Online (Sandbox Code Playgroud)