没有'访问控制 - 允许起源 - 反应+ Axios

问题描述:

在我开始之前,我需要作出声明,我是自学noob('你好')。没有'访问控制 - 允许起源 - 反应+ Axios

我试图从克罗地亚API银行网站http://api.hnb.hr/tecajn获取数据。调用看起来是这样的:

[{ 
    "broj_tecajnice": "162", 
    "datum": "2017-08-24", 
    "drzava": "Australija", 
    "sifra_valute": "036", 
    "valuta": "AUD", 
    "jedinica": 1, 
    "kupovni_tecaj": "4,942956", 
    "srednji_tecaj": "4,957829", 
    "prodajni_tecaj": "4,972702" 
    },{ 
    "broj_tecajnice": "162", 
    "datum": "2017-08-24", 
    "drzava": "Kanada", 
    "sifra_valute": "124", 
    "valuta": "CAD", 
    "jedinica": 1, 
    "kupovni_tecaj": "4,979337", 
    "srednji_tecaj": "4,994320", 
    "prodajni_tecaj": "5,009303" 
    }, ] 

我现在面临的问题是No 'Access-Control-Allow-Origin' header

XMLHttpRequest cannot load http://api.hnb.hr/tecajn. Response to preflight request doesn't pass access control check: 
No 'Access-Control-Allow-Origin' header is present on the requested resource. 
Origin 'http://localhost:3000' is therefore not allowed access. 

我学习和使用React的UI和axios的GET请求。

import React, { Component } from 'react'; 
import axios from 'axios'; 

class App extends Component { 
    constructor(props) { 
    super(props); 
    this.state = {  
     test: null 
    } 
    } 

    componentDidMount(){ 
    const getData =() => {  
     const url = ' http://api.hnb.hr/tecajn'; 

    axios.get(url, { 
     headers: { 'Access-Control-Allow-Origin': '*'} 
    }).then((response) => { 
     console.log("response", response); 
      this.setState({ 
      test: response.data 
     });   
    }) 
    .catch((error) => { 
     if(error instanceof Error) { 
      console.log(error.message); 
     } else { 
      console.log(error.data); 
     } 
    });  
    } 
    getData(); 
    } 

    render() { 
    return (
     <div> 
     <div className='container'> 
      <p>test</p> 
     </div> 
     </div> 
    ); 
    } 
} 

export default App; 

I'we看着几乎所有的文件,我仍然不明白这一点。

https://www.html5rocks.com/en/tutorials/cors 
https://stackoverflow.com/questions/35588699/response-to-preflight-request-doesnt-pass-access-control-check 

我试了很多组合,我需要帮助。 我需要使用Express.js吗?我需要做些什么els。我不知道。

如果你有好时间帮助我,我将不胜感激。
TY!

+0

了解同源政策。你不能那样做。 – SLaks

+0

从React(同构应用程序)调用API调用时出现['Access-Control-Allow-Origin'问题]的可能重复(https://stackoverflow.com/questions/41497674/access-control-allow-origin-issue-when -api-call-made-from-react-isomorphic-ap) – azium

+1

为了解决缺乏来自'http:// api.hnb.hr/tecajn'的CORS支持的问题,你可以使用'const url ='https:/ /cors-anywhere.herokuapp.com/http:// api.hnb.hr/tecajn''在你的代码中,有关解释,请参阅https://stackoverflow.com/questions/20035101/no-access-control-允许产集管是存在的 - 上的请求的资源/ 42744707#42744707 – sideshowbarker

您将需要使用CORS服务来设置正确的标题并解决此问题。我遇到过这个问题很多次了。查看本网站http://crossorigin.me/