【问题标题】:'Access-Control-Allow-Origin' error when getting data from the API with Axios (React)使用 Axios (React) 从 API 获取数据时出现“Access-Control-Allow-Origin”错误
【发布时间】:2017-03-03 06:10:12
【问题描述】:

我收到“XMLHttpRequest 无法加载 https://example.com。请求的资源上不存在 'Access-Control-Allow-Origin' 标头。因此不允许访问 Origin 'http://localhost:8000'。”

这是我的 componenDidMount(),我正在使用 axios 从我的 API 中获取数据。

componentDidMount() {
   this.serverRequest = axios.get(this.props.source).then(event =>{    
     this.setState({
          title: event.data[0].name
      });
   });
}

我在终端上使用“python -m SimpleHTTPServer”来运行“http://localhost:8000”。

我使用的是 Chrome 浏览器,如果我打开 Chrome CORS 插件(以启用跨源资源共享),该应用程序可以运行,并且我会看到 DOM 上的 API 显示的数据。但是我知道使用CORS插件不好,那么我应该如何正式修复'Access-Control-Allow-Origin'错误?

使用 Axios,我可以通过某种方式添加 dataType: "jsonp",如果这样可以解决吗?

【问题讨论】:

  • 您需要在您的服务器上允许 CORS 才能让您的应用运行
  • @ShubhamKhatri 但是在本地主机上怎么样?
  • 您使用的是哪个后端服务器。你需要在服务器上启用 CORS,不需要在 localhost 上做任何事情

标签: javascript reactjs axios


【解决方案1】:

当您尝试从另一个域访问某个域中的内容时,出于安全原因,这是浏览器做出的限制。你克服了这个,你需要在你的标题中设置以下内容

Access-Control-Request-Method
Access-Control-Request-Headers

许多网站都限制了 CORS。实现目标的最佳方法是将您的 python 服务器作为代理。请参阅示例。

//Request from the client/browser

http://localhost:8000/loadsite?q=https%3A%2F%2Fexample.com

//In your server

 1. Handle the request
 2. Get the query param(url of the website)
 3. Fetch it using your python server
 4. Return the fetching data to the client.

这应该可行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-11
    • 1970-01-01
    • 2017-12-29
    • 2018-02-02
    • 2021-06-17
    • 2017-06-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多