简体   繁体   English

没有“ Access-Control-Allow-Origin”标头,但无权访问API

[英]No 'Access-Control-Allow-Origin' header but no access to API

I'm trying to use the UK Parliament API but I'm hitting this error: 我正在尝试使用UK Parliament API,但遇到此错误:

XMLHttpRequest cannot load http://findyourmp.parliament.uk/api/search?q=london&f=js . XMLHttpRequest无法加载http://findyourmp.parliament.uk/api/search?q=london&f=js No 'Access-Control-Allow-Origin' header is present on the requested resource. 所请求的资源上没有“ Access-Control-Allow-Origin”标头。 Origin ' http://example.com ' is therefore not allowed access. 因此,不允许访问来源“ http://example.com ”。

I know what it means, but there's no JSONP option and I can't edit Parliament's API. 我知道这是什么意思,但是没有JSONP选项,而且我无法编辑议会的API。 How can I get around this? 我该如何解决? Could I route the request through a PHP file on my server that I can allow access to or would that not solve the problem? 我可以通过服务器上允许访问的PHP文件路由请求,还是不能解决问题?

Here's my code: 这是我的代码:

var search_term = $('#input').val();
var url = 'http://findyourmp.parliament.uk/api/search?q=' + search_term + '&f=js';

$.getJSON(url, function(jd) {
    $('#div').html('<p>Constituency: ' + jd.constituency_name + '</p>');
});

EDIT 编辑

API here. 这里的API。

yes using serverside "proxy" would solve the problem, as the Access-Control-Allow_Origin is for client-side calls 是的,使用服务器端“代理”可以解决问题,因为Access-Control-Allow_Origin用于客户端调用

simple php snippet 简单的PHP代码段

$search_term = "find";
$url = "http://findyourmp.parliament.uk/api/search?q=".$search_term."&f=js";
return file_get_contents($url);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM