2016-10-21 35 views
1

我得到一個「XMLHttpRequest無法加載https://example.com。'Access-Control-Allow-Origin'請求的資源。原因'http://localhost:8000'因此不允許訪問。「使用Axios從API獲取數據時出現'Access-Control-Allow-Origin'錯誤(React)

這是我componenDidMount(),和我使用Axios公司從我的API獲取數據。

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

我使用 「蟒蛇-m SimpleHTTPServer」 在終端上,運行 'http://localhost:8000'。

我使用的是Chrome瀏覽器,如果我打開Chrome的插件CORS(啓用跨源資源共享),應用程序的作品,我看到了DOM API的顯示的數據。但是我知道使用CORS插件是不好的,所以我應該如何正式修復'Access-Control-Allow-Origin'錯誤?

有了愛可信,可我莫名其妙地添加數據類型:「JSONP」,是否會解決這個問題?

+0

你需要讓你的服務器上CORS爲你的應用程序的功能 –

+0

@ShubhamKhatri但如何在本地主機上? – userden

+0

您使用的是哪個後端服務器。您需要在服務器上啓用CORS,無需在本地主機上執行任何操作 –

回答

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. 

這應該有效。

相關問題