执行批量请求时,Youtube JavaScript客户端API交叉来源错误

时间:2018-05-16 16:46:14

标签: cors youtube-api youtube-data-api redux-thunk youtube-javascript-api

我尝试使用Youtube JavaScript client API从Youtube后端获取特定数量类别的n个最受欢迎的视频。

据我了解,您无法在一个请求中获取多个类别的最热门视频。因此,我试图利用Youtube client API batching feature。要仅针对一个特定类别获取n个最受欢迎的视频,请点击以下端点

GET https://www.googleapis.com/youtube/v3/videos?part=snippet%2Cstatistics%2CcontentDetails&chart=mostPopular&maxResults=12&videoCategoryId=20&key={YOUR_API_KEY}

我尝试在React组件中批量处理3个不同类别的3个请求:

// somewhere in the component
this.props.fetchMostPopularVideosByCategory([17, 18, 19], 12);

//...
// action creator code
export function fetchMostPopularVideosByCategory(categoryIds, amount = 12) {
  const requests = categoryIds.map(categoryId => {
    return buildApiRequest('GET',
      '/youtube/v3/videos',
      {
        part: 'snippet,statistics,contentDetails',
        chart: 'mostPopular',
        maxResults: amount,
        videoCategoryId: categoryId,
        fields: ...
      }, null);
  });

  return executeBatchApiRequest(requests, 'fetchMostPopularVideosByCategory');
}

export function executeBatchApiRequest(requests, actionType) {
  return (dispatch) => {
    const batch = window.gapi.client.newBatch();
    for (const req in requests) {
      batch.add(req);
    }

    batch.execute((response) => {
      dispatch({
        type: actionType,
        payload: response,
      })
    });
  };
}

请注意,一旦我收到结果,我正在使用redux / redux thunk来发送操作。我已经从Google's boilerplate code复制了buildApiRequest方法(只需切换代码部分右上角的开关)。

如果我没有使用batching功能,只是执行如下所示的标准请求,我就不会遇到任何问题。

export function executeApiRequest(requestMethod, path, params, properties, actionType) {
  return (dispatch) => {
    const request = buildApiRequest(requestMethod, path, params, properties);
    request.execute((response) => {
      dispatch({
        type: actionType,
        payload: response,
      })
    });
  }
}

但是,如果我使用window.gapi.client.newBatch()对其进行批处理,则会出现跨源错误:

  

错误:抛出了跨源错误。 React无法访问   开发中的实际错误对象。看到   https://reactjs.org/docs/cross-origin-errors.html了解更多信息。

[控制台输出]

  

无法加载   https://apis.google.com/_/scs/apps-static/[...]/cb=gapi.loaded_0:不   '访问控制允许来源'标题出现在请求的上   资源。起源' http://localhost:3000'因此是不允许的   访问。如果不透明的响应满足您的需求,请设置请求   模式为' no-cors'在禁用CORS的情况下获取资源。

我不知道为什么只有在我尝试使用批处理功能时才会出现这种情况。我检查了上面提到的React URL,但我无法找到解决方案。没有批处理,我根本不会得到这个错误?关于如何解决这个问题的任何提示?

0 个答案:

没有答案