标签: fetch-api

AbortController.abort(reason),但是reason在到达fetch catch子句之前就丢失了

我正在实施可中止的获取调用

中止我的页面上的提取基本上有两个原因:

  • 用户决定不再等待 AJAX 数据并单击按钮;在这种情况下,用户界面会显示一条消息“呼叫/任何中断”
  • 用户已移动到页面的另一部分,并且不再需要正在获取的数据;在这种情况下,我不希望用户界面显示任何内容,因为它只会让用户感到困惑

为了区分这两种情况,我计划使用reason该方法的参数AbortController.abort,但 fetch 调用中的 .catch 子句始终收到一个DOMException('The user aborted a request', ABORT_ERROR).

我试图提供一个不同的DOMException作为情况 2 中止的原因,但差异丢失了。

有没有人找到如何将有关中止原因的信息发送到 fetch .catch 子句?

javascript google-chrome domexception fetch-api abortcontroller

4
推荐指数
1
解决办法
3669
查看次数

ServiceWorker:没有针对javascript触发请求的FetchEvent?

我正在使用Chrome stable 46.

我有一个非常基本的网站.一个button.onclick fetch('a')和一个<a>打开的标签b.这两个URL ab不存在的,我打算抓住他们的服务人员和刚刚返回new Response().

如果我单击提取的按钮a,服务工作者不参与,我收到404错误.
但是,如果我点击进入的链接,b服务工作人员就会获取并返回响应.

问题:为什么服务工作者没有为fetch('a')请求获取任何FetchEvent ?

请参阅以下文件

HTML

<html>
  <body>
    <p><button onclick="fetch('a');">fetch a</button></p>
    <p><a href="b">go to b</a></p>
    <script src="js.js" defer></script>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

js.js

navigator.serviceWorker.register('sw.js');
Run Code Online (Sandbox Code Playgroud)

sw.js

self.onfetch = function(event) {
  var request = event.request;
  event.respondWith(
    caches.match(request).then(function(response) {
      return new Response('here is your onfetch response');
    })
  );
};
Run Code Online (Sandbox Code Playgroud)

javascript fetch asp.net-web-api service-worker fetch-api

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

如何使用GitHub Fetch API polyfill

我想使用polyfill,fetch()以便我的代码使用GitHub Fetch Polyfill在Safari 运行,但我不确定如何使用它.

根据其文档,我可以安装它:

$ npm install whatwg-fetch --save
Run Code Online (Sandbox Code Playgroud)

我已经完成了这一步.

我已经尝试过这个,但它不起作用:

var fetch = require('whatwg-fetch') // does not work
Run Code Online (Sandbox Code Playgroud)

我怎么想使用fetch polyfill?


参考文献:

javascript npm polyfills fetch-api

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

React Native Fetch API不返回我的调用

对不起标题中的笑话.

我目前正在探索反应原生的fetch API,但我遇到了一些我无法解决的问题.

所以,我试图从服务器获取一条消息,我用以下方式使用fetch API调用它:

var serverCommunicator = {
    test: function() {
        fetch(baseUrl  , {
          method: 'GET',
          headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
          }
        })
        .then((response) => response.text())
        .then((responseText) => {
             return (JSON.stringify(responseText));
        })
        .catch((error) => {
          console.warn(error);
        }).done();
    },
module.exports = serverCommunicator;
Run Code Online (Sandbox Code Playgroud)

当我仅使用console.log(responseText)我的日志测试时给了我正确的消息.但是,现在当我想尝试将代码中的内容作为消息放入View中时,它不会按预期返回.以下列方式调用它:

import Method from '../Services/Methods';
.
.
.
<View style={styles.card}>
   <CardView
      message={Method.test()} 
    />
Run Code Online (Sandbox Code Playgroud)

我可以看到在调用它时如何正确调用函数测试,但由于某种原因,它不会编写消息.

javascript react-native fetch-api

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

如何从Fetch API获得进展?

我正在使用 $.ajax,我可以这样做:

var xhr = new window.XMLHttpRequest();
//Upload progress
xhr.upload.addEventListener("progress", function(evt){
  if (evt.lengthComputable) {
    var percentComplete = evt.loaded / evt.total;
    //Do something with upload progress
    console.log(percentComplete);
  }
}, false);
Run Code Online (Sandbox Code Playgroud)

但是,当我使用fetch api时,我该怎么办?

var fData = new FormData();
fData.append("userfile",document.getElementById("file").files[0]);
fetch("/", {method:"POST",body:fData}).then(function(res){});
Run Code Online (Sandbox Code Playgroud)

javascript progress fetch-api

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

获取Api:无法从localhost获取数据

我一直在尝试使用nativescript创建一个Android应用程序.我正在使用fetch模块从我的服务器获取响应.当我试图从httpbin.org/get获得响应时,它没关系.但是当我试图获得响应时从我的本地服务器,我收到网络请求失败.错误.

发送到httpbin.org/get-

return fetchModule.fetch("https://httpbin.org/get").then(response => { return response.text(); }).then(function (r) {
        console.log(r);
    }, function (e) {
            console.log(e);
        }); 
Run Code Online (Sandbox Code Playgroud)

发送到localhost:8000/api-

return fetchModule.fetch("http://localhost:8000/api").then(response => { return response.text(); }).then(function (r) {

       console.log(r);

}, function (e) {

        console.log(e);
    });
Run Code Online (Sandbox Code Playgroud)

当我尝试通过请求模块从localhost:8000/api获取纯node.js的响应.它工作正常.但是现在,我不知道如何使用fetch模块在nativescript中解决这个问题.

android node.js nativescript fetch-api laravel-5.2

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

从状态API设置提取的数据将不起作用

我正在尝试使用Django和ReactJS构建一个用于教育目的的新闻/文章网站.

目前,我在Django中创建了一个文章模型,并为ReactJS设置了一个API来与之交谈.每篇文章都有标题,图片,内容,精选和快速阅读属性.特色和快速读取是布尔值.我已经成功设置了我的ReactJS组件来获取所有文章,但是我无法过滤那些既article.featured真实article.quickreads又真实的文章.目前我的组件有三种状态:文章,精选和快速阅读.这是它目前的样子:

class Api extends React.Component{
  constructor(){
    super();
    this.state = {
      articles: null,
      featured: null,
      quickreads: null
    }
  }
  componentDidMount(){
    fetch("http://127.0.0.1:8000/articles/articlesapi/").then(request => request.json()).then(response => this.setState({articles: response}))
    var featured = this.state.articles.filter(article => article.featured === true)
    var quickreads = this.state.articles.filter(article => article.quickreads === true)
    this.setState({featured: featured, quickreads: quickreads})
  }
  render(){
    return (
      <p>Hello  World</p>
    )
  }
}
Run Code Online (Sandbox Code Playgroud)

虽然组件获得所有的文章就无法更新featuredquickreads.我收到以下错误:

Uncaught TypeError: Cannot read property 'articles' of undefined at componentDidMount (eval at <anonymous>)...
Run Code Online (Sandbox Code Playgroud)

为什么会这样?

javascript asynchronous reactjs fetch-api

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

在获取请求中设置Content-Type不起作用

我正在对服务器执行远程获取请求。有效负载为JSON格式,因此我想将Content-Type标头更改为application/json。我已使用以下代码执行此操作:

let email = document.getElementById("email").value
let password = document.getElementById("password").value

const body = {"email":email, "password":password}
const headers = new Headers({
    "Content-Type": "application/json",
    "Content-Length": JSON.stringify(body).length
})
const options = {
    method: "POST",
    mode: "no-cors",
    headers: headers,
    body: JSON.stringify(body)
}
console.log(options)
const response = await fetch('http://xx.xx.xx.xxx/login', options)
const json = await response.json()
console.log(json)
Run Code Online (Sandbox Code Playgroud)

但是,在Chrome开发者工具控制台中,Content-Type请求的标头仍为text/plain;charset=UTF-8。我究竟做错了什么?

javascript json reactjs fetch-api

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

React JS Fetch返回空响应但Postman不返回

我有一个React JS应用程序试图登录基于令牌的API(我也在开发,使用Laravel 5.5和Laravel Passport).我正在尝试实现基本登录(使用用户名和密码登录,一旦验证就从服务器接收令牌,使用该令牌进行将来的查询).

我用来获取的代码如下:

function loginApi(username, password) {
    return fetch(loginUrl, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            grant_type: 'password',
            client_id: clientId,
            client_secret: clientSecret,
            username: username,
            password: password
        })

   }).then(handleApiErrors)
     .then(response => response.json)
}
Run Code Online (Sandbox Code Playgroud)

值得注意的是,它还没有完全完成,因为我目前只是想确定我要回复的反应.

我已经解决了遇到的正常问题,比如CORS问题,但是我现在遇到的问题是来自API的响应只是......空的.即使在Chrome的开发人员工具的"网络"标签中,如果我直接检查请求,则响应为空.

开发工具1

开发工具2

但是,如果我做了确切的相同与邮差查询,结果正是我所期望的.

邮差

这可能是什么问题?为什么完全相同的查询会返回不同的结果?

post promise laravel reactjs fetch-api

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

POST请求使用fetch()返回204 No Content

我正在向node.js服务器发出POST请求,但我无法让它工作.这是我的要求:

const headers = {
  'Accept': 'application/json',
  'Content-Type': 'application/json',
  'Authorization': 'this-can-be-anything',
};

export const postVote = (id, vote) =>
  fetch(`${uri}/posts/${id}`, {
    method: 'POST',
    headers,
    body: JSON.stringify({options: vote}),
  }).then(response => response.json())
    .then(data => data)
    .catch(err => console.log(err));
Run Code Online (Sandbox Code Playgroud)

该函数接受'id'和'vote'两个字符串.id被用作请求中URI的一部分,并且投票作为选项提供,因此API知道如何处理它.两个参数都正确传递:

id = '8xf0y6ziyjabvozdd253nd'
vote = 'upVote'
Run Code Online (Sandbox Code Playgroud)

这是一个指向服务器/ API的GitHub存储库的链接:

Udacity Readable API

以及触发请求时网络的屏幕截图:

在此输入图像描述 在此输入图像描述

更新:添加了显示状态200的第二个屏幕截图.虽然它显示了这个并且似乎已经成功,但它仍然没有发布到服务器并且信息保持不变.

javascript post node.js fetch-api

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