标签: fetch-api

检测 PHP 中的 fetch 请求

如何在 PHP 中检测来自Fetch API 的请求?我目前正在使用以下方法来检测 AJAX 请求:

$context['isAJAX'] = (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
Run Code Online (Sandbox Code Playgroud)

理想情况下,我可以以类似的方式检测 Fetch 请求。有没有人有任何技术来实现这一点?

php fetch-api

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

为什么 Fetch API 调用不返回响应标头?

我正在构建一个注册表单,并有以下 API 调用来发布表单:

const request = new Request('http://localhost:4300/auth/', {
 method: 'POST',
 headers: new Headers({
   'Accept'       : 'application/json',
   'Content-Type' : 'application/json',
 }),
 body: JSON.stringify({ user: data })
});

fetch(request).then(response => {
    console.log(response);
    const auth = response.headers.get('Authorization');
    console.log(auth)
});
Run Code Online (Sandbox Code Playgroud)

问题是response.headers.get('Authorization')作为null. 即使我查看 Chrome 的 Network XHR 请求,我也会看到 API 服务器发送的响应标头。

为什么 React 没有response.headers通过上面的请求向我提供?

谢谢

javascript fetch cors reactjs fetch-api

3
推荐指数
1
解决办法
4140
查看次数

无法捕获 HTTP 请求错误代码 429

使用fetchApi我向端点发出 POST 请求并捕获如下错误:

fetch(new Request(url, {
  method: 'POST',
  headers: { ...defaultHeaders, ...headers } ,
  credentials: 'include',
  body: JSON.stringify(body)
})).then(
  // handle correct reponse
).catch(
  if (err.status === 401) {
       // handle error nicely
    } else if (err.status === 429) {
       // handle error differently
    } else {
      // handle error yet another way
    }
);
Run Code Online (Sandbox Code Playgroud)

虽然 401 错误按预期处理,但当端点以 429 响应时,代码

else if (err.status === 429) {
       // handle error differently
    } 
Run Code Online (Sandbox Code Playgroud)

永远不会被执行。

EDIT1:在 429 的情况下永远不会达到整个捕获

javascript/浏览器对 401 和 …

javascript http fetch-api

3
推荐指数
1
解决办法
2956
查看次数

如何防止在 node.js 中两次调用相同 URL 的获取

我要对后端进行 x 次调用。其中一些指向相同的 URL。我正在缓存结果。但我的问题是,如果我使用相同的 URL 立即调用 loadCached 两次(或多次),它实际上也会调用两次 fetch,因为在第一次 fetch 解决之前缓存没有 url。因此,缓存仅在成功完成一次提取(=已解决)时才起作用。我如何改进代码以等待第一次获取被解析以避免重复查询?

function loadCached(url) {
  let cache = loadCached.cache || (loadCached.cache = new Map());

  if (cache.has(url)) {
    return Promise.resolve(cache.get(url)); // (*)
  }

  return fetch(url)
    .then(response => response.text())
    .then(text => {
      cache[url] = text;
      return text;
    });
}
Run Code Online (Sandbox Code Playgroud)

我正在使用 promise.all() 等待 loadCached 解决。

javascript caching node.js promise fetch-api

3
推荐指数
1
解决办法
2210
查看次数

使用 React Native 将数组发送到服务器以获取一些数据

我正在尝试使用给定的数据从服务器获取数据。我正在使用以下代码:

    const details = {
      'function': 'getUsers',
    };
    const formBody = 
    Object.keys(details).map(key=>encodeURIComponent(key)+
    '='+encodeURIComponent(details[key])).join('&');
    console.log(formBody);
    fetch(url, {
      method: 'POST',
      credentials: 'include',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
        'Cookie': 'XPIDER_SID=' + this.props.text
      },
      body: formBody
      }).then((response) => response.json())
        .then((responseJson) => {
          if (responseJson.status === 'okay') {
            this.setState({ users: responseJson.users });
          } else {
             this.setState({ error: responseJson.error });
          }
      })
Run Code Online (Sandbox Code Playgroud)

直到现在它都很好用。现在我必须发送一个数据数组,但是当我在细节常量中写入一个数组时,由于 formBody,服务器不接受该数组。在formBody中,整个请求都是字符串,所以数组转为字符串。我怎样才能用这个发送一个数组?或者你们知道其他选择吗?谢谢你 !

arrays api http-post react-native fetch-api

3
推荐指数
1
解决办法
7329
查看次数

如何从api获取reactjs中的图像?

在使用 JWT 令牌进行验证后,我正在从 nodejs API 获取图像。我在浏览器中收到 GET 200 ok 响应网络标题和图片可以在预览中看到,但我不能在我的应用程序中使用它。

我肯定做错了什么。请让我知道从 API 显示图像的正确方法。在我的后端 nodejs 上,我使用 res.sendFile 发送文件。

class Card extends Component {
 constructor({props, pic, token}) {
super(props, pic, token);
this.state = { 
  pic: pic,
};

urlFetch(data) {
 fetch(data, { 
 headers: new Headers({
 'authorization': `Bearer ${this.props.token}`, 
 'Content-Type': 'application/json'
 })
})
.then(response => {
 if (response.statusText === 'OK') {
  return data   // OR return response.url
  }
 })
}

render() {
const { pic } = this.state;

 return (
        <div>
          <img style={{width: 175, …
Run Code Online (Sandbox Code Playgroud)

javascript node.js reactjs fetch-api

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

状态 204 显示 response.ok

在我的 ASP.NET Core API 后端,我Status 204在没有数据时发送,但我在前端注意到,我的fetch调用仍然显示response.ok.

两个问题:

  1. 这是正常行为吗?我想,这是一个成功的调用,所以响应可能没问题,但它让我失望了。
  2. 检查的最佳方法是Status 204什么?

我的React/Redux应用程序中的当前代码如下所示:

export const apiCall = () => {
   return (dispatch) => fetch("/api/get", fetchOptions)
      .then((response) => {
         if(response.ok) {
            // Do something
         } else {
            // Couldn't get data!
         }
      })
};
Run Code Online (Sandbox Code Playgroud)

这是我处理fetch调用的标准代码块。我应该如何修改它来处理Status 204场景?

javascript http-status-codes fetch-api

3
推荐指数
1
解决办法
4964
查看次数

Java脚本获取返回200但没有数据

我需要在下拉列表中显示世界上所有的国家。所以我找到了这个 api 端点END POINT LINK。当我将此端点链接复制并粘贴到我的 Web 浏览器中时,我收到了包含所有数据的响应。(国家);

当我尝试将其嵌入到项目中时。

getCountries() {
      try {
       
        fetch(`https://restcountries.eu/rest/v1/all`).then(data =>
          console.log(data)
        );
        
      } catch (error) {
        console.log("HERE ERROR COMES", error);
      }
    }
Run Code Online (Sandbox Code Playgroud)

它确实转到 fetch 方法的 then 块。但给了我输出 在此处输入图片说明

这里没有什么叫做数据。即使我得到了成功的回应。为什么会发生这种情况?这与cors错误有关吗?

javascript fetch-api

3
推荐指数
1
解决办法
2879
查看次数

Javascript - 在 localhost 上使用 fetch 和 URL 参数

我有一个 NodeJS 服务器运行在我电脑的 3001 端口上。我可以使用fetch访问本地主机的端点,就像这样:fetch("/api_endpoint")

但是,我还想在我的 GET 请求中包含 url 参数。

通常,我可以通过这样做来包含 url 参数:

const url = new URL("localhost:3001")
const params = { sources: JSON.stringify(this.state.sources), timeRange: JSON.stringify(this.state.timeRange), minReacts: this.state.minReacts }
url.search = new URLSearchParams(params)
let data = await fetch(url)
Run Code Online (Sandbox Code Playgroud)

但是,这会引发错误:

获取 API 无法加载 localhost:3001?sources=%5B%22Confessions%22%2C%22Summer+Confessions%22%2C%22Timely+Confessions%22%5D&timeRange=%5B%222017-01-12T23%3A35%6AZ 22%2C%222019-01-12T23%3A35%3A07.667Z%22%5D&minReacts=20。对于 CORS 请求,URL 方案必须是“http”或“https”。

如何创建一个与 localhost 一起使用的获取请求,该请求也使用 URL 参数?

编辑:

添加http://到前面并不能解决问题。

访问 ' http://localhost:3001/?sources=%5B%22Confessions%22%2C%22Summer+Confessions%22%2C%22Timely+Confessions%22%5D&timeRange=%5B%222017-01-13T00% 3A00%3A17.309Z%22%2C%222019-01-13T00%3A00%3A17.310Z%22%5D&minReacts=20 ' from origin ' http://localhost:3000 ' 已被 CORS 策略阻止:No 'Access- Control-Allow-Origin' 标头存在于请求的资源上。如果不透明响应满足您的需求,请将请求的模式设置为“no-cors”以在禁用 CORS 的情况下获取资源。

javascript localhost url-parameters fetch-api

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

Cloudflare Worker TypeError:一次性使用的主体

我正在尝试使用Cloudflare Worker将 POST 请求代理到另一台服务器。

它抛出了一个 JS 异常——通过包含在一个 try/catch 博客中,我已经确定错误是:

TypeError: A request with a one-time-use body (it was initialized from a stream, not a buffer) encountered a redirect requiring the body to be retransmitted. To avoid this error in the future, construct this request from a buffer-like body initializer.

我原以为这可以通过简单地复制 Response 来解决,以便它不被使用,如下所示:

return new Response(response.body, { headers: response.headers })

这是行不通的。我在这里缺少流式传输与缓冲的什么?

addEventListener('fetch', event => {

  var url = new URL(event.request.url);

  if (url.pathname.startsWith('/blog') || url.pathname === '/blog') {
    if (reqType …
Run Code Online (Sandbox Code Playgroud)

javascript fetch-api cloudflare-workers

3
推荐指数
1
解决办法
1010
查看次数