【问题标题】:redux isomorphic fetch Access-Control-Allow-Originredux 同构获取 Access-Control-Allow-Origin
【发布时间】:2016-06-20 14:44:48
【问题描述】:

我编写了一个使用 webpack-dev-server 在本地运行的 redux 应用程序。 (端口 8080)。我正在尝试连接到在端口 9000 本地运行的 Web 服务。

我连接网络服务的代码如下

return fetch(`http://localhost:9000/movies/${dimensionName.toLowerCase()}list`)
  .then(response => response.json())
  .then(json =>
    dispatch(receivedDimensionAttributesSuccess(dimensionName, json))
  )
  .catch(error =>
    dispatch(receivedDimensionAttributesError(dimensionName, error))
  );

这会收到错误

Fetch API cannot load http://localhost:9000/movies/yearlist. No 'Access-
Control-Allow-Origin' header is present on the requested resource. Origin 
'http://localhost:8080' is therefore not allowed access. If an opaque response 
serves your needs, set the request's mode to 'no-cors' to fetch the resource 
with CORS disabled.

我搜索了这个问题并找到了这个帖子

Access Control Allow Origin header not present with fetch api call

但我不喜欢涉及完全切换到不同库/中间件的解决方案。

如何解决同构提取库的问题。

【问题讨论】:

标签: reactjs redux


【解决方案1】:

look at me,this works

你必须使用

let header = new Headers({
        'Access-Control-Allow-Origin':'*',
        'Content-Type': 'multipart/form-data'
});

而不是

let defaultOptions = {
    url:'',
    method:'POST',
    mode: 'cors',
    headers:{
        'Access-Control-Allow-Origin':'*'
    },
    body:null,
};

启用cors

【讨论】:

    【解决方案2】:

    您可以简单地添加 {mode:'no-cors',} 来禁用 No 'Access- Control-Allow-Origin' 标头。欲了解更多信息,您可以参考以下网址:

    https://developers.google.com/web/ilt/pwa/working-with-the-fetch-api

    return fetch(`http://localhost:9000/movies/${dimensionName.toLowerCase()}list`**,{mode:'no-cors'**,})
      .then(response => response.json())
    

    【讨论】:

    • 这会通过完全删除读取响应的尝试来防止错误出现。由于代码需要读取响应,这并不能解决问题。
    【解决方案3】:

    Access-Control-Allow-Origin 是您可以在客户端控制的东西。是对浏览器的安全限制,需要与服务器协商。

    服务器可以从任何端点检索数据,但对于浏览器应用程序则不同。出于安全原因,您只能通过 XHR 从您已加载网页的同一服务器加载数据。 如果您需要从不同的服务器(比如外部 API)加载数据,浏览器会要求服务器响应以表明您被允许。

    请参阅http://www.acuriousanimal.com/2011/01/27/working-with-the-javascript-xmlhttprequest-object.html“跨域请求”部分中的说明

    【讨论】:

      【解决方案4】:

      你可以阅读这个https://developer.mozilla.org/zh-CN/docs/Web/API/GlobalFetch/fetch

      fetch(url[, init])

      设置初始化参数允许跨域请求

      试试

      【讨论】:

        猜你喜欢
        • 2022-09-27
        • 1970-01-01
        • 2017-06-15
        • 2016-09-30
        • 2015-06-17
        • 2017-12-29
        • 2019-02-07
        • 2013-09-09
        相关资源
        最近更新 更多