标签: fetch-api

需要改变什么来防止服务人员的双重请求?

请不要标记为重复。这与此处的其他类似问题并不完全相同。它更具体且完全可重现。

  1. 克隆这个仓库。
  2. yarn && yarn dev
  3. 转至localhost:3000(F12)->Applications->Service Workers 并确保已安装 Service Worker。
  4. 转到“网络”选项卡并刷新几次(F5)
  5. 观察网络请求如何加倍。

我所看到的示例: 在此输入图像描述


或者,如果您想手动执行此操作,请按照以下说明操作:

  1. yarn create-next-app app_name
  2. cd app_name && yarn
  3. 在公共文件夹中,创建名为的文件service-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)
  1. 打开pages/index.js并在下面import Head from "next/head";粘贴以下代码:
if (typeof window !== "undefined" && …
Run Code Online (Sandbox Code Playgroud)

service-worker fetch-api progressive-web-apps next.js

5
推荐指数
1
解决办法
4016
查看次数

如何为 fetch API 调用设置较大的请求正文

我有一个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-api

5
推荐指数
1
解决办法
1284
查看次数

fetch 返回语法错误:JSON 中位置 0 处出现意外标记 T

我正在尝试使用 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)

javascript fetch reactjs react-native fetch-api

5
推荐指数
2
解决办法
2万
查看次数

从 Chrome 获取 API 响应 2 分钟后抛出错误

我在 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请求中没有超时参数。

我尝试使用等待和异步,但它没有成功,并且还从下面的链接中得到答案。

删除 Fetch API 默认超时

我想获取后端服务器花费超过2分钟的数据。谁可以帮我这个事?

javascript reactjs fetch-api

5
推荐指数
1
解决办法
1144
查看次数

Elasticsearch 和 fetch:不支持 Content-Type 标头 [text/plain;charset=UTF-8]

我正在尝试让 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)

javascript node.js express elasticsearch fetch-api

5
推荐指数
0
解决办法
796
查看次数

NextJS - getServerSideProps - 错误 400 - 错误请求

我在 NEXT JS 中使用 getServerSideProps 函数进行 fetch 时遇到问题。当我开始使用这个框架时,我可能做得不好。访问外部 API 的所有凭据都是正确的。当我在 React 中使用相同的参数进行获取时,它会为我带来信息,但是使用 Next JS 它会返回 400 - 错误请求。

\n

我将所有参数放在下面同一个块代码中,以便于理解。我使用像“”这样的凭据参数来保护隐私。他们是正确的,没有任何问题。

\n

注意:我相信我一定以错误的方式使用了 getServerSideProps 函数。我不知道除了编写函数之外是否还需要对 Next JS 进行任何配置。换句话说,这里显示的是我到目前为止实际写的内容。该程序直接从index.js 调用。

\n

这是文件夹结构:

\n

文件夹结构

\n

ListOrders 是我渲染页面的地方。它从我执行提取操作的 getServerSideProps 函数接收 {orders} 作为 props。

\n
const 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)

javascript fetch-api server-side-rendering axios next.js

5
推荐指数
0
解决办法
1万
查看次数

React:异步和等待不适用于 fetch

我在 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 json reactjs fetch-api

5
推荐指数
2
解决办法
3万
查看次数

为什么我的微型 API 没有响应主体?

对于我的小型 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)

javascript api perl cgi fetch-api

5
推荐指数
1
解决办法
1024
查看次数

CORS 阻止对资源的访问:如何在 firebase 云功能中修复?

是的,我有可怕的 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)

node.js cors firebase fetch-api google-cloud-functions

5
推荐指数
1
解决办法
5865
查看次数

无法使用 Web Video Kit API 将视频发布到 Tiktok

我正在尝试使用此端点将视频上传到 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)

javascript node.js fetch-api axios tiktok

5
推荐指数
1
解决办法
6977
查看次数