我正在编写一个与 Twitter API 集成的相当基本的 Web 应用程序。我正在使用 jQuery 和 AJAX 请求 Twitter 所需的身份验证令牌,但我违反了异步跨站点请求策略或其他任何策略。
我会使用 JSONP,但 Twitter API 需要一个 POST。我已阅读我应该使用中间代理。我不知道这涉及什么并且找不到任何资源?我可以用 PHP 编写。
谁能解释一下什么是代理页面?
更新
在阅读下面接受的答案后,我编写了一个 PHP 代理脚本,这就是我想出并开始工作的:
<?php
class proxy {
public $serviceURL;
public $postString;
public $headers;
public $response;
public function __construct($url) {
$this->serviceURL = $url;
$this->postStringify($_POST);
}
private function postStringify($postArray) {
$ps = '';
foreach($postArray as $key => $value) {
$ps .= $key . '=' . $value . '&';
}
rtrim($ps, '&');
$this->postString = $ps;
}
private function isCurlInstalled() {
return (in_array('curl', get_loaded_extensions())) ? true : false;
}
public function makeRequest() {
if ($this->isCurlInstalled()) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->serviceURL);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POSTFIELDS, $this->postString);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $this->headers);
$this->response = curl_exec($ch);
if ($this->response === false) $this->response = curl_error($ch);
curl_close($ch);
} else {
$this->response = 'Need to install Curl!';
}
return $this->response;
}
public function debug() {
var_dump($this->response);
}
}
?>
在 AJAX 请求调用的另一个文件中:
<?php
include ('proxy.php');
ini_set('display_errors',1);
error_reporting(E_ALL);
$consumerKey = 'myKEY!';
$consumerSecret = 'mySecret!';
$bearerTokenCredentials = $consumerKey . ':' . $consumerSecret;
$base64TokenCredentials = base64_encode($bearerTokenCredentials);
$authProxy = new proxy('https://api.twitter.com/oauth2/token/');
$authProxy->headers = array(
'Content-Type: application/x-www-form-urlencoded',
'Authorization: Basic ' . $base64TokenCredentials,
);
$response = $authProxy->makeRequest();
if (is_null($response)) $authProxy->debug(); else echo $response;
?>