标签: fetch-api

在 fetch api 中使用类似 fiddler 的代理

如何使用 Fetch API 设置代理。我正在开发一个 node.js 应用程序,我想看看 HTTPS 响应的响应正文。我正在使用这个使用 node http 的 npm 包:https : //www.npmjs.com/package/isomorphic-fetch

我试图设置 env 变量,如:

set https_proxy=http://127.0.0.1:8888
set http_proxy=http://127.0.0.1:8888
set NODE_TLS_REJECT_UNAUTHORIZED=0
Run Code Online (Sandbox Code Playgroud)

但它似乎只适用于请求 NPM 节点模块。

我总是收到以下消息:

http://127.0.0.1:8888
(node:30044) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): FetchError: request to https://www.index.hu failed, reason: read ECONNRESET
Run Code Online (Sandbox Code Playgroud)

javascript proxy fiddler node.js fetch-api

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

Fetch APIs - 它是阻塞代码还是非阻塞代码?

我已经看了Fetch API几天了。

在学习的过程中,我遇到了“使用fetch()不会阻止你的 DOM”这一说法,因为它使用了 Promise。

很高兴继续学习这些教程并查看一些新教程,我​​看到一个人在演示文稿中说“使用fetch()确实会阻塞你的 DOM”。

谁能告诉我它是两者中的哪一个?

javascript dom promise ecmascript-6 fetch-api

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

使用 chrome --print-to-pdf --headless 太快地打印 html?

我使用 cmd 并输入“chrome --headless --disable-gpu --print-to-pdf=d:\project\test.pdf http://localhost:8085/t1/index.html?data=http:/ /localhost:8085/1/mock.json "

生成的pdf只是空白。我认为原因是我使用 fetch 来获取 mock.json 和

dom 没有足够的时间来完全渲染。如果我只是导入 mock.json 和

pdf可以完美呈现。那么,有什么方法可以延迟打印到 pdf 的过程吗?

谢谢!

pdf google-chrome fetch-api google-chrome-headless

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

为什么 Body.json() 会返回一个 Promise?

我从 JS 开始,实际上喜欢异步方面(来自 Python),但我不确定为什么有些函数会返回 Promise。具体来说,下面的代码 usingfetch让我想知道返回的是什么json():

fetch('https://freegeoip.net/json/8.8.8.8')
  .then((response) => {
    return response.json()
  })
  .then((json) => {
    Object.keys(json).forEach((key) => {
      console.log("got " + key)
    })
  })
Run Code Online (Sandbox Code Playgroud)

撇开流不谈,我们在 a 之后得到的 HTTP 响应GET是一个文本块,稍后由客户端解释以提取标头、正文和其他有趣的元素 - 作为 HTTP 内容分析的一部分。

关键是这个文本块是一个整体,所以第一个then()已经有了整个响应——为什么解析 JSON 正文是一个异步操作,forEach与第二个不同then()?

换句话说,为什么我不能让以下代码工作?

fetch('https://freegeoip.net/json/8.8.8.8')
  .then((response) => {
    Object.keys(response.json()).forEach((key) => {
      console.log("got " + key)
    })
  })
Run Code Online (Sandbox Code Playgroud)

注意:如果第一个代码运行不正确(带有ERR_BLOCKED_BY_CLIENT),请尝试禁用您的广告拦截器。第二个是故意不正确的。

javascript json promise fetch-api

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

嵌套的 try、catch 和 async、await 请求

我正在尝试使用 fetch() 发出三个请求,每个请求都取决于前一个请求的结果。如果任何请求失败,我想抛出一个自定义错误。

这种模式有效,除非最里面的请求失败,它会抛出所有三个错误。如果中间请求失败,则抛出中间和外部错误。

我该如何解决这个问题,让它只从请求失败的级别抛出错误?有没有更好的方法来写这个?

async function requests() {
  try {
    let response1 = await fetch();
    if (response1.ok) {
      try {
        let response2 = await fetch();
        if (response2.ok) {
          try {
            let response3 = await fetch();
            if (response3.ok) {
              let jsonResponse3 = response3.json();
              return jsonResponse3;
            }
            throw new Error('Request 3 failed');
          } catch (error) {
            console.log(error);
          }
        }
        throw new Error('Request 2 failed');
      } catch (error) {
        console.log(error);
      }
    }
    throw new Error('Request 1 failed');
  } catch (error) {
    console.log(error); …
Run Code Online (Sandbox Code Playgroud)

javascript try-catch async-await fetch-api

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

反应导航 state.params 不起作用

它不工作。我尝试了一切。什么都行不通。state.params如果您制作高级应用程序,则根本不存在。

我对反应“导航”有这个问题。它在手册中说 params 对象应该在那里https://reactnavigation.org/docs/navigation-prop.html#state-the-screen-s-current-state-route但它不是。

id当我链接到屏幕 2 时,我在屏幕 1 中设置了这样的参数:

 <TouchableWithoutFeedback onPress={ ()=> this.props.navigation.navigate('FontsTab', { id: item.id }) } style={styles.listHeader} >
                <View  style={styles.listRowContainer}>
                    <View  style={styles.listinside1Container}>
                        <Image  style={styles.listImage} source={item.icon} />
                        <View  style={styles.listContainer} onPress={(event) => this._selectedItem(item.text)}  >
                            <Text style={styles.listHeader} >
                              {item.title}
                            </Text>
                            <Text  style={styles.listValue} >{item.value}</Text>
                            <Image 
                                style={{width: 50, height: 50}}
                                source={{uri: item.img}}
                            />

                        </View>
                    </View>

                                </View>
            </TouchableWithoutFeedback>
Run Code Online (Sandbox Code Playgroud)

但它不起作用。在屏幕 2 中,我不能使用state.params:

     <ScrollView style={styles.container}>
          <Text>{ JSON.stringify(this.props.navigation)}</Text>
          <Text>TEST{ state.params }</Text>
          <Image
              style={{width: 150, height: 150}}
              source={{uri: this.state.dataSource.img}}
          />
          <Text …
Run Code Online (Sandbox Code Playgroud)

react-native fetch-api react-navigation

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

获取期间无法在 try-catch 中捕获 403

我正在使用 ReactJS 发出放置请求,但是,当我输入错误的电子邮件/密码组合时,即使我试图捕获所有错误并将它们显示在 Chrome 上,我也会将其登录errorDiv:

在此处输入图片说明

async connect(event) {
  try {
    const userObject = {
      username: this.state.userName,
      password: this.state.password
    };
    if (!userObject.username || !userObject.password) {
      throw Error('The username/password is empty.');
    }
    let response = await fetch(('someurl.com'), {
      method: "PUT",
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(userObject)
    });
    let resJSON = await response.json();
    if (!response.ok) {
      throw Error(resJSON.message);
    }
    console.info(resJSON.message);
    console.info(resJSON.message.auth_token);
    window.location = "/ledger/home";
  } catch (e) {
    document.getElementById("errorDiv").style.display = 'block';
    document.getElementById("errorDiv").innerHTML = e;
  }
}
Run Code Online (Sandbox Code Playgroud)

javascript put http-status-code-403 reactjs fetch-api

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

fetch 的重定向和授权标头的预期行为是什么?(Safari 与其他 Mac 浏览器的行为不同)

简而言之,当使用带有 fetch api 的授权标头并遵循重定向时,Chrome、FireFox 和 Opera(在 Mac 上)在第二个请求中包含授权标头。但是,Safari (12.0.1) 没有。从fetch api 规范和问题 #553我的理解是应该包含标题。这是对 fetch 应该如何工作的正确理解吗?

这是我用于 Safari 的解决方法的简化代码,但我想知道是否我做错了什么导致了 Safari 的行为,或者是否有更好的解决方法。

export async function loadData(token) {
  const opts = {headers: {Authorization: `Bearer ${token}`}, credentials: 'include', redirect: 'follow'};
  let response = await fetch('/api/data', opts);

  // Work around for Safari not including headers in redirected request
  if (response.status === 401 && response.redirected) {
    response = await fetch(response.url, opts);
  }

  if (response.ok) {
    return response.json();
  }

  return null; …
Run Code Online (Sandbox Code Playgroud)

safari redirect webkit http-authentication fetch-api

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

当 http 响应状态为 400 时,使用 fetch api 获取自定义错误消息

我有 Python Flask (v 1.0.0) 后端,它返回状态为 400 的 http 响应和自定义错误消息

return Response('My custom errror message', 400)
Run Code Online (Sandbox Code Playgroud)

在我的前端,我使用 Fetch API 对后端进行了 API 调用:

fetch(url, options)
  .then(response => response.json())
  .then(response => console.log(response))
  .catch(error => console.log(error));
Run Code Online (Sandbox Code Playgroud)

由于 400 是一个BAD REQUEST,fetch直接进入catch,我所拥有的只是TypeError: Failed to fetch消息。

如何在前端获取自定义错误消息而不是Failed to fetch消息?它在 DevTools 中可见,所以我希望它应该以fetch某种方式可用?

在此处输入图片说明在此处输入图片说明

javascript http fetch-api

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

在 JavaScript 中检测网页上的 fetch API 请求

背景:我正在使用 Shopify ScriptTag,它允许我在店面添加 JavaScript 文件。我只有那个脚本文件。

当前行为:有一个选项“立即购买”,允许客户跳过Add To Cart直接结账。当他们点击一口,Shopify发送取() POST请求checkouts.json创建结账。

问题:我需要在我自己的 JavaScript 文件中检测这个“获取请求发生”。

self.addEventListener('fetch', event => {
    console.log("event happened");
});
Run Code Online (Sandbox Code Playgroud)

我试过Fetch Event API,但它似乎只在Service Worker范围内工作。

有没有可能检测到这一点?

就像我们可以通过使用原型继承覆盖其open方法来检测XMLHttpRequest一样。

javascript fetch fetch-api

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