在 react-redux 应用程序中使用 JSONP

Posted

技术标签:

【中文标题】在 react-redux 应用程序中使用 JSONP【英文标题】:Using JSONP in react-redux application 【发布时间】:2017-11-22 02:39:46 【问题描述】:

我只是想解决由missing headers 在请求中引起的CORS headers 问题,因此倾向于使用JSONP

关于如何在react-redux 应用程序中使用JSONP 有任何建议/想法吗?请问如何配置和使用?

【问题讨论】:

【参考方案1】:

在你的 react 组件中,调度一个被中间件捕获的动作。中间件应该调用 jsonp 端点,可能使用 jquery 的 $.ajax 方法。我也喜欢fetchJsonp 库。然后,您的中间件应该使用 ajax 或 fetchJsonp 接收到的数据发送一个新操作,这些数据应该被您的 reducer 捕获,并更改状态。

【讨论】:

【参考方案2】:

在大多数情况下,我在 React 应用程序中使用 fetch:

    // payload is your post data
    const payload = data: 'test';
    const options = 
      method: 'POST',
      headers: 
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      ,
      body: JSON.stringify(payload),
      cors: true, // allow cross-origin HTTP request
      credentials: 'same-origin' // This is similar to XHR’s withCredentials flag
    ;

    // SEND REQUEST
    fetch('http://example.com/', options).then((response) => 
      // TODO
    ).catch((error) => 
      // TODO
    );

【讨论】:

以上是关于在 react-redux 应用程序中使用 JSONP的主要内容,如果未能解决你的问题,请参考以下文章