2015-10-05 76 views
1

的API V3我目前使用此代码做的GET请求的搜索jQuery中:YouTube视频搜索与使用curl返回错误

$.get("https://www.googleapis.com/youtube/v3/videos?id=c8a3_9ecqBA&key=MYAPIKEY&part=snippet,contentDetails", function(data) { 
    console.log(data); 
}); 

,并且数据在控制台中正确返回。但我想在做PHP(使用AJAX)同样的事情,所以我一直在想:

// Get cURL resource 
$curl = curl_init(); 

// Set some options - we are passing in a useragent too here 
curl_setopt_array($curl, array(
    CURLOPT_RETURNTRANSFER => 1, 
    CURLOPT_URL => "https://www.googleapis.com/youtube/v3/videos?q=Eminem&key=MYAPIKEY&part=snippet&type=video&maxResults=20", 
    CURLOPT_USERAGENT => "Simple Test" 
)); 

// Send the request & save response to $resp 
$resp = curl_exec($curl); 

// Close request to clear up some resources 
curl_close($curl); 

echo $resp; 

但回应是:

{ 
    "error": { 
     "errors": [ 
      { 
       "domain": "usageLimits", 
       "reason": "ipRefererBlocked", 
       "message": "There is a per-IP or per-Referer restriction configured on your API key and the request does not match these restrictions. Please use the Google Developers Console to update your API key configuration if request from this IP or referer should be allowed.", 
       "extendedHelp": "https://console.developers.google.com" 
      } 
     ], 
     "code": 403, 
     "message": "There is a per-IP or per-Referer restriction configured on your API key and the request does not match these restrictions. Please use the Google Developers Console to update your API key configuration if request from this IP or referer should be allowed." 
     } 
} 

如何解决呢?

+0

这是我的公开API密钥,并被配置为只能在配置的域上工作,所以,我没有看到问题分享这个... – Igor

+1

您可以使用'CURLOPT_REFERER'设置标题的'Referer' – Federkun

+0

它的工作@Federico 。 Thx兄弟!作出回答,以便我可以将其标记为已解决 – Igor

回答

2

错误的原因是请求需要启用Referer。您可以通过将CURLOPT_REFERER选件添加到您的curl_setopt_array配置中进行设置。