标签: fetch-api

try..catch没有捕获异步/等待错误

也许我误解了如何捕捉错误async/await应该来自像这样的文章https://jakearchibald.com/2014/es7-async-functions/和这个http://pouchdb.com/2015/03/05/taming- the-async-beast-with-es7.html,但是我的catch块没有捕获400/500.

async () => {
  let response
  try {
   let response = await fetch('not-a-real-url')
  }
  catch (err) {
    // not jumping in here.
    console.log(err)
  }
}()
Run Code Online (Sandbox Code Playgroud)

有关codepen的例子,如果有帮助的话

javascript try-catch async-await fetch-api

14
推荐指数
1
解决办法
6484
查看次数

使用redux-form和Fetch API进行服务器验证

如何使用redux-form和Fetch API 进行服务器端验证?文档中提供了" 提交验证 "演示,其中说服务器端验证的推荐方法是从onSubmit函数返回一个promise.但是我应该把这个承诺放在哪里?据我所知,onSubmit函数应该是我的动作.

<form onSubmit={this.props.addWidget}>...
Run Code Online (Sandbox Code Playgroud)

this.props.addWidget实际上是我的行动,如下所示.

import fetch from 'isomorphic-fetch';
...
function fetchAddWidget(widget, workspace) {
    return dispatch => {
        dispatch(requestAddWidget(widget, workspace));
        return fetch.post(`/service/workspace/${workspace}/widget`, widget)
            .then(parseJSON)
            .then(json => {
                dispatch(successAddWidget(json, workspace));
                DataManager.handleSubscribes(json);
            })
            .catch(error => popupErrorMessages(error));
    }
}

export function addWidget(data, workspace) {
    return (dispatch, getState) => {
        return dispatch(fetchAddWidget(data, workspace));
    }
}
Run Code Online (Sandbox Code Playgroud)

如您所见,我使用fetch API.我期望fetch将返回promise并且redux-form将捕获它但是这不起作用.如何使它与示例中的承诺一起工作?

同样从演示中我无法理解this.props.handleSubmit函数应该提供什么.对我来说,演示不解释这一部分.

validation es6-promise redux fetch-api redux-form

14
推荐指数
1
解决办法
7713
查看次数

获取本地文件的请求不起作用

我正在尝试在本地文件中发出请求,但我不知道我何时尝试在计算机上显示错误.是否可以获取项目中的文件?

 // Option 1
 componentDidMount() {
     fetch('./movies.json')
     .then(res => res.json())
     .then((data) => {
        console.log(data)
     });
 }

 error: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 at App.js: 10 -->  .then(res => res.json())

 // Option 2
 componentDidMount() {
    fetch('./movies.json', {
       headers : { 
         'Content-Type': 'application/json',
         'Accept': 'application/json'
       }
    })
   .then( res => res.json())
   .then((data) => {
        console.log(data);
   });
 }

 error1: GET http://localhost:3000/movies.json 404 (Not Found) at App.js:15 --> fetch('./movies.json', {
 error2: Uncaught (in promise) SyntaxError: Unexpected token …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs fetch-api

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

将withCredentials设置为新的ES6内置HTTP请求API:Fetch

如何设置withCredentials=truefetch其回报的承诺.以下是正确的:

fetch(url,{
   method:'post',
   headers,
   withCredentials: true
});
Run Code Online (Sandbox Code Playgroud)

我认为MDN文档谈到了关于http请求的所有内容,除非这一点:withCredentials

javascript xmlhttprequest ecmascript-6 fetch-api

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

在Javascript中拦截Fetch()API响应和请求

我想拦截Javascript中的fetch API请求和响应.

例如:在发送请求之前要拦截请求URL并且一旦获得响应就想拦截响应.

以下代码用于拦截所有XMLHTTPRequest的响应.

(function(open) {
 XMLHttpRequest.prototype.open = function(XMLHttpRequest) {
    var self = this;
    this.addEventListener("readystatechange", function() {
        if (this.responseText.length > 0 && this.readyState == 4 && this.responseURL.indexOf('www.google.com') >= 0) {
            Object.defineProperty(self, 'response', {
                get: function() { return bValue; },
                set: function(newValue) { bValue = newValue; },
                enumerable: true,
                configurable: true
            });
            self.response = 'updated value' //Intercepted Value 
        }
    }, false);
    open.apply(this, arguments);
};
})(XMLHttpRequest.prototype.open);
Run Code Online (Sandbox Code Playgroud)

我想为Fetch()API实现相同的功能.

提前致谢..

javascript ajax xmlhttprequest interceptor fetch-api

13
推荐指数
4
解决办法
7489
查看次数

松弛传入webhook:请求头字段预检响应中的Access-Control-Allow-Headers不允许Content-type

我尝试在浏览器中通过fetch API发布松弛消息:

fetch('https://hooks.slack.com/services/xxx/xxx/xx', {
  method: 'post',
  headers: {
    'Accept': 'application/json, text/plain, */*',
    'Content-type': 'application/json'
  },
  body: JSON.stringify({text: 'Hi there'})
})
  .then(response => console.log)
  .catch(error => console.error);
};
Run Code Online (Sandbox Code Playgroud)

我收到以下错误消息:

Fetch API cannot load:
https://hooks.slack.com/services/xxxxxxx/xxxxx. 
Request header field Content-type is not allowed by Access-Control-Allow-Headers in preflight response.
Run Code Online (Sandbox Code Playgroud)

该怎么办?

javascript content-type cors slack fetch-api

13
推荐指数
2
解决办法
3213
查看次数

在 React JS 中使用 fetch 处理响应状态

我刚开始学习 ReactJS。现在我想知道当我使用 fetch 发出 API 请求时如何处理响应状态。这是我的代码:

componentDidMount(){
    this.setState({ isLoading: true })
    var id = this.props.match.params.id        

    const api = `bla/bla/${id}`;

    console.log("start call api")
    fetch(api)
        .then((response) => {
            if(response.status === 200){
                console.log("SUCCESSS")
                return response.json();     
            }else if(response.status === 408){
                console.log("SOMETHING WENT WRONG")
                this.setState({ requestFailed: true })
            }
        })
        .then((data) => {
            this.setState({ isLoading: false, downlines: data.response })
            console.log("DATA STORED")
        })
        .catch((error) => {
            this.setState({ requestFailed: true })
        })
    console.log("end call api")
}
Run Code Online (Sandbox Code Playgroud)

我关闭了我的连接以进行测试408,但我的加载仍然出现。

render(){
     const { isLoading, requestFailed } = this.state; …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs fetch-api

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

在提取API中启用CORS

我收到以下错误消息,我无法继续

无法加载https://site/data.json:对预检请求的响应未通过访问控制检查:所请求的资源上没有'Access-Control-Allow-Origin'标头。因此,不允许访问源' http:// localhost:8080 '。如果不透明的响应满足您的需求,请将请求的模式设置为“ no-cors”,以在禁用CORS的情况下获取资源。localhost /:1未捕获(承诺)TypeError:无法获取

我正在尝试CORS在我的react js文件中启用,但无法获得预期的结果。我已经安装了chrome扩展程序,并且可以正常工作。但是要在生产站点中使用它,我需要在代码中启用它。我应该如何正确安排代码以启用CORS

fetch(URL, {
  mode: 'cors',
  headers: {
    'Access-Control-Allow-Origin':'*'
  }
})
  .then(response => response.json())
  .then(data => {
Run Code Online (Sandbox Code Playgroud)

javascript reactjs fetch-api

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

使用 cURL 访问 API 可以正常工作,但不能使用 Fetch API

我知道这已经在 SO 上解决了很多次,但所有的答案大多都在“向服务器添加某个标头”的脉络中。在这种情况下,API (Shopify) 工作得很好,可以通过 curl 轻松访问。

我已经尝试过使用 Axios 库和 Fetch API。

  • 我已经试过了所有的价值referrermode以及referrerPolicy在提取选项。
  • 我已经确认我的 BasicAuth 凭据是正确的。
  • 我在多个浏览器中尝试过。
  • 我已经从 localhost、localhost.com(在我的 /etc/hosts 中设置该值)和具有真实域名的服务器进行了尝试。

我不明白为什么这在 cURL 中可以很好地工作,但在 fetch() 中却不能。

这是我的代码的缩短版本:

const apiKey = 'mykey';
const apiPassword = 'mypass';
const apibase = 'https://my-shop-domain.myshopify.com/admin/';
const endpoint = 'locations.json';

var headers = new Headers({
   "Authorization": "Basic " + btoa( apiKey + ':' + apiPassword ),
});

    fetch( apibase + endpoint {
      method: 'GET',
      headers: headers,
      mode: 'no-cors',
      // …
Run Code Online (Sandbox Code Playgroud)

javascript curl shopify fetch-api

13
推荐指数
1
解决办法
3071
查看次数

相当于 XHR 或 Ajax 库中的 Fetch 'no-cors' 模式?

有没有办法在现有的(大多数浏览器支持的)HTTP 请求中编写 fetch {mode: 'no-cors'} ?例如,我想知道是否可以翻译以下内容:

fetch(url, { mode: 'no-cors'})
.then(function (response) {
  console.log(response);
});
Run Code Online (Sandbox Code Playgroud)

转换成某种 XMLHttpRequest 或 Ajax。我尝试了几种方法,但它们的行为有所不同 - 我只想要 fetch 返回的不透明响应。

谢谢!

ajax xmlhttprequest cors fetch-api

13
推荐指数
0
解决办法
5649
查看次数