【问题标题】:Async await and fetch always returning error异步等待和获取总是返回错误
【发布时间】:2019-08-05 07:12:53
【问题描述】:

我正在使用 fetch 获取数据,但总是收到此错误:

  async fetchPhotos(token, placeid) {
    const _PLACEID = placeid ? placeid : this.props.attributes.placeid;
    const _TOKEN = token ? token : this.props.attributes.token;

    if (!_TOKEN || !_PLACEID) {
      return false;
    }

    const url = `https://maps.googleapis.com/maps/api/place/details/json?key=${_TOKEN}&placeid=${_PLACEID}`;
    console.log(url);

    try {
      const response = await fetch(url);
      console.log(response);
    } catch (error) {
      console.log('you got an error bro: ' + error.toString());

      this.setState({
        apiResponseCode: '400',
        apiErrorMessage: error.toString(),
        loading: false,
      });
    }
  }

但是,如果我手动将 url 插入浏览器,它可以正常工作,所以我不知道为什么它总是出错?

【问题讨论】:

  • 你的错误信息是什么?
  • 你有没有在构造函数中绑定你的函数来访问this.props?

标签: reactjs async-await


【解决方案1】:

所以事实证明该错误与 CORS 相关。我需要通过代理服务器运行我的获取请求。

所以我没有直接调用谷歌,而是像这样调用服务器:

const url = 'http://myproxyserver.test/wp-json/google-places/v1/get-reviews';

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-02
    • 2018-02-15
    • 2020-04-22
    • 2018-06-30
    • 2019-09-29
    • 2020-03-13
    • 2021-11-01
    相关资源
    最近更新 更多