我收到一条“XMLHttpRequest 无法加载 https://example.com 。请求的资源上不存在 'Access-Control-Allow-Origin' header 。因此不允许访问 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 插件(以启用跨源资源共享),应用程序就会运行,并且我会看到 API 在 DOM 上显示的数据。但我知道使用 CORS 插件是不好的,那么我应该如何正式修复“Access-Control-Allow-Origin”错误呢?
使用 Axios,我可以以某种方式添加 dataType: "jsonp",如果这样可以修复它吗?
最佳答案
当您尝试从另一个域访问某个域中的内容时,这是浏览器出于安全原因而做出的限制。您克服了这个问题,您需要在 header 中设置以下内容
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.
这应该有效。
关于javascript - 使用 Axios (React) 从 API 获取数据时出现“Access-Control-Allow-Origin”错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40168040/