I am trying to learn how to parse APIs using javascript and so I am trying to get some json through some get calls.
我正在尝试学习如何使用javascript解析API,所以我试图通过一些get调用获得一些json。
In my script I have
在我的剧本中我有
<script>
function foo() {
var request = window.superagent;
var url = 'http://www.google.ca';
request
.get(url, function(response) {
console.log(response);
})
.set('Accept', 'application/json');
}
foo();
</script>
No matter what url I use, I always get this error
无论我使用什么网址,我总是会收到此错误
XMLHttpRequest cannot load http://www.google.ca/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://server.com' is therefore not allowed access.
(index):22 Error: Origin is not allowed by Access-Control-Allow-Origin
at s.crossDomainError (https://cdnjs.cloudflare.com/ajax/libs/superagent/1.2.0/superagent.min.js:1:7899)
at XMLHttpRequest.s.end.D.onreadystatechange (https://cdnjs.cloudflare.com/ajax/libs/superagent/1.2.0/superagent.min.js:1:8551)
I tried using various example get request urls like wikipedia, nba stats, google etc...that work fine when I enter the url into my browser but it does not work when I try to use javascript to download the data.
我尝试使用各种示例获取请求网址,如*,nba统计数据,谷歌等...当我在我的浏览器中输入网址时工作正常,但当我尝试使用javascript下载数据时它不起作用。
I am using a local apache2 server on my ubuntu laptop. I am also using the superagent library for javascript, but i also tried using jquery and ajax and it's the same error.
我在我的ubuntu笔记本电脑上使用本地apache2服务器。我也使用superagent库的javascript,但我也尝试使用jquery和ajax,这是同样的错误。
so apparently I need to use a url that uses cors. The thing is
显然我需要使用一个使用cors的网址。事情是
this tutorial just did a requests.get(url) which was the nba stats url and got his data. He did not get an error? How can I use a url that doesn't use cors to get data?
本教程只是做了一个requests.get(url),它是nba stats url并得到了他的数据。他没有得到错误?如何使用不使用cors获取数据的网址?
1 个解决方案
#1
0
CORS is implemented on the browser end as well, to not allow javascript load malicious content from unknown sites. You should also try using the CORS plugin if you are still trying to scrap on the client side.
CORS也在浏览器端实现,不允许javascript加载来自未知站点的恶意内容。如果您仍在尝试在客户端废弃,也应该尝试使用CORS插件。
#1
0
CORS is implemented on the browser end as well, to not allow javascript load malicious content from unknown sites. You should also try using the CORS plugin if you are still trying to scrap on the client side.
CORS也在浏览器端实现,不允许javascript加载来自未知站点的恶意内容。如果您仍在尝试在客户端废弃,也应该尝试使用CORS插件。