使用 jQuery AJAX 请求和 PHP 代理检索数据时出现问题
Problem retrieving data using jQuery AJAX request with PHP proxy
我正在为一家公司面试,他们给了我一份带回家的作业,我可以在没有时间限制的情况下完成。其中一项规范是我使用 PHP API 代理来绕过他们的 API 的 CORS。除了 JQuery 之外,我不允许为此使用任何 PHP 或 JS 库。我是 PHP 的新手,习惯用 React 获取数据,所以我觉得有点不适应。我发现在我看来它应该是一个解决方案:
https://github.com/joseftw/php-rest-proxy
...但我无法让它工作。每当我加载页面并检查控制台时,它只会为 GET 和 POST 请求(在 Firefox 上)保持 <empty string>
。我知道调用正在触发,因为如果我添加它们,它们会执行 console.log('test')
。那么数据呢?
这是我的 PHP 代理文件的代码:
<?php
$url = $_REQUEST["url"];
if(!$url) {
echo "You need to pass in a target URL.";
return;
}
$response = "";
switch (getMethod()) {
case 'POST':
$response = makePostRequest(getPostData(), $url);
break;
case 'GET':
$response = makeGetRequest($url);
break;
default:
echo "This proxy only supports POST AND GET REQUESTS.";
return;
}
echo $response;
function getMethod() {
return $_SERVER["REQUEST_METHOD"];
}
function getPostData() {
return http_build_query($_POST);
}
function makePostRequest($data, $url) {
$httpHeader = array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data));
return makePutOrPostCurl('POST', $data, true, $httpHeader, $url);
}
function makeGetRequest($url) {
$ch = initCurl($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
function makePutOrPostCurl($type, $data, $returnTransfer, $httpHeader, $url) {
$ch = initCurl($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $type);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, $returnTransfer);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
function initCurl($url) {
$httpHeader = array(
'Content-Type: application/x-www-form-urlencoded');
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $httpHeader);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1667.0 Safari/537.36');
return $ch;
}
?>
这是我 script.js 文件中的 AJAX 请求:
$(document).ready(function () {
$.ajax({
url: 'proxy.php?url=https://reqres.in/api/users',
type: 'POST',
data: { name: 'Zlatan Ibrahimovic' },
success: function (data) {
console.log(data);
},
});
$.get('proxy.php?url=https://reqres.in/api/users', function (data) {
console.log(data);
});
});
我提供的端点来自示例 API,而不是公司的 API。尽管如此,我仍然无法使用 proxy/AJAX 组合来处理任何事情。这是第 2 天,我正在转动轮子。谁能指出我正确的方向?我是完全偏离 PHP 代理设置,还是其他原因?
我在脚本主体中使用 JS 脚本。一旦我得到响应,我就使用 document.getElementById('result') 将它发送回 dom --- 查看内部 html 正文;当我尝试使用 /users 时,即使在 link 上有结果,我也没有得到任何有趣的东西。我认为您要访问的 link 是 /user。我为 url 添加了一个 isset 验证。否则,当您不在导航器 url.
中添加 ?url 时,它会中断
<?php
$url = null;
if (isset($_REQUEST["url"])) {
$url = $_REQUEST["url"];
}
if(!$url) {
echo "You need to pass in a target URL.";
return;
}
$response = "";
switch (getMethod()) {
case 'POST':
$response = makePostRequest(getPostData(), $url);
break;
case 'GET':
$response = makeGetRequest($url);
break;
default:
echo "This proxy only supports POST AND GET REQUESTS.";
return;
}
echo $response;
function getMethod() {
return $_SERVER["REQUEST_METHOD"];
}
function getPostData() {
return http_build_query($_POST);
}
function makePostRequest($data, $url) {
$httpHeader = array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data));
return makePutOrPostCurl('POST', $data, true, $httpHeader, $url);
}
function makeGetRequest($url) {
$ch = initCurl($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
print_r($response);
curl_close($ch);
return $response;
}
function makePutOrPostCurl($type, $data, $returnTransfer, $httpHeader, $url) {
$ch = initCurl($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $type);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, $returnTransfer);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
function initCurl($url) {
$httpHeader = array(
'Content-Type: application/x-www-form-urlencoded');
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $httpHeader);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1667.0 Safari/537.36');
return $ch;
}
?>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="result"></div>
<script type="module">
addEventListener('DOMContentLoaded', () => {
console.log('ok');
const xhtml = new XMLHttpRequest();
xhtml.onreadystatechange = (res) => {
if ((res.target.status === 201 || res.target.status === 200) && res.target.readyState === 4) {
console.log('----------------res object--------------------' + "<::::>");
console.log(res, "res");
console.log('----------------status--------------------' + "<::::>");
console.log(res.target.status);
console.log('------------------readyState------------------' + "<::::>");
console.log(res.target.readyState);
console.log('------------------response------------------' + "<::::>");
console.log(res.target.response);
console.log('------------------responseText------------------' + "<::::>");
console.log(res.target.responseText);
document.getElementById('result').innerText = res.target.responseText;
}
}
xhtml.open('POST', 'https://reqres.in/api/user');
xhtml.send(JSON.stringify({
url: 'proxy.php?url=https://reqres.in/api/user',
type: 'POST',
data: {name: 'Zlatan Ibrahimovic'},
}));
});
</script>
</body>
</html>
如果您想使用提供的 url 从这一行替换...xhtml.open('POST', 'https://reqres.in/api/user');
const url = JSON.parse(`<?php echo $url?>`);
xhtml.open('POST', url);
xhtml.send(JSON.stringify({
url: 'proxy.php?url=' + url,
type: 'POST',
data: {name: 'Zlatan Ibrahimovic'},
}));
我想出了如何让它发挥作用。 PHP:
<?php
// getting the baseURL from the request
$baseURL = $_REQUEST['url'];
// getting the request method sent in to the proxy
function getRequestMethod() {
return $_SERVER["REQUEST_METHOD"];
}
// getting the POST data from a POST request
function getPostData() {
return http_build_query($_POST);
}
function makeGetRequest($baseURL) {
$ch = curl_init();
$fullURL = $baseURL.<URLparams here>;
curl_setopt($ch, CURLOPT_URL, $fullURL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$response = curl_exec($ch);
curl_close($ch);
if($e = curl_error($ch)) {
echo $e;
} else {
$json = json_decode($response, true);
return print_r($json);
}
}
function makePostRequest($baseURL) {
$ch = curl_init();
$data = http_build_query($_POST);
curl_setopt($ch, CURLOPT_URL, $baseURL);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
if($e = curl_error($ch)) {
echo $e;
} else {
$json = json_decode($response, true);
return print_r($json);
}
}
$response = "";
switch (getRequestMethod()) {
case 'GET':
$response = makeGetRequest($baseURL);
break;
case 'POST':
$response = makePostRequest($baseURL);
break;
default:
echo "There has been an error";
return;
}
echo $response;
JS:
$(document).ready(function () {
$.ajax({
url: 'proxy.php?url=<Endpoint here>',
type: 'POST',
data: {
partnerName: 'applicant',
partnerPassword: 'd7c3119c6cdab02d68d9',
partnerUserID: 'expensifytest@mailinator.com',
partnerUserSecret: 'hire_me',
},
success: function (data) {
console.log(data);
},
});
$.get(
'proxy.php?url=<Endpoint here>',
function (data) {
console.log(data);
}
);
});
我正在为一家公司面试,他们给了我一份带回家的作业,我可以在没有时间限制的情况下完成。其中一项规范是我使用 PHP API 代理来绕过他们的 API 的 CORS。除了 JQuery 之外,我不允许为此使用任何 PHP 或 JS 库。我是 PHP 的新手,习惯用 React 获取数据,所以我觉得有点不适应。我发现在我看来它应该是一个解决方案:
https://github.com/joseftw/php-rest-proxy
...但我无法让它工作。每当我加载页面并检查控制台时,它只会为 GET 和 POST 请求(在 Firefox 上)保持 <empty string>
。我知道调用正在触发,因为如果我添加它们,它们会执行 console.log('test')
。那么数据呢?
这是我的 PHP 代理文件的代码:
<?php
$url = $_REQUEST["url"];
if(!$url) {
echo "You need to pass in a target URL.";
return;
}
$response = "";
switch (getMethod()) {
case 'POST':
$response = makePostRequest(getPostData(), $url);
break;
case 'GET':
$response = makeGetRequest($url);
break;
default:
echo "This proxy only supports POST AND GET REQUESTS.";
return;
}
echo $response;
function getMethod() {
return $_SERVER["REQUEST_METHOD"];
}
function getPostData() {
return http_build_query($_POST);
}
function makePostRequest($data, $url) {
$httpHeader = array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data));
return makePutOrPostCurl('POST', $data, true, $httpHeader, $url);
}
function makeGetRequest($url) {
$ch = initCurl($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
function makePutOrPostCurl($type, $data, $returnTransfer, $httpHeader, $url) {
$ch = initCurl($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $type);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, $returnTransfer);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
function initCurl($url) {
$httpHeader = array(
'Content-Type: application/x-www-form-urlencoded');
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $httpHeader);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1667.0 Safari/537.36');
return $ch;
}
?>
这是我 script.js 文件中的 AJAX 请求:
$(document).ready(function () {
$.ajax({
url: 'proxy.php?url=https://reqres.in/api/users',
type: 'POST',
data: { name: 'Zlatan Ibrahimovic' },
success: function (data) {
console.log(data);
},
});
$.get('proxy.php?url=https://reqres.in/api/users', function (data) {
console.log(data);
});
});
我提供的端点来自示例 API,而不是公司的 API。尽管如此,我仍然无法使用 proxy/AJAX 组合来处理任何事情。这是第 2 天,我正在转动轮子。谁能指出我正确的方向?我是完全偏离 PHP 代理设置,还是其他原因?
我在脚本主体中使用 JS 脚本。一旦我得到响应,我就使用 document.getElementById('result') 将它发送回 dom --- 查看内部 html 正文;当我尝试使用 /users 时,即使在 link 上有结果,我也没有得到任何有趣的东西。我认为您要访问的 link 是 /user。我为 url 添加了一个 isset 验证。否则,当您不在导航器 url.
中添加 ?url 时,它会中断<?php
$url = null;
if (isset($_REQUEST["url"])) {
$url = $_REQUEST["url"];
}
if(!$url) {
echo "You need to pass in a target URL.";
return;
}
$response = "";
switch (getMethod()) {
case 'POST':
$response = makePostRequest(getPostData(), $url);
break;
case 'GET':
$response = makeGetRequest($url);
break;
default:
echo "This proxy only supports POST AND GET REQUESTS.";
return;
}
echo $response;
function getMethod() {
return $_SERVER["REQUEST_METHOD"];
}
function getPostData() {
return http_build_query($_POST);
}
function makePostRequest($data, $url) {
$httpHeader = array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data));
return makePutOrPostCurl('POST', $data, true, $httpHeader, $url);
}
function makeGetRequest($url) {
$ch = initCurl($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
print_r($response);
curl_close($ch);
return $response;
}
function makePutOrPostCurl($type, $data, $returnTransfer, $httpHeader, $url) {
$ch = initCurl($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $type);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, $returnTransfer);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
function initCurl($url) {
$httpHeader = array(
'Content-Type: application/x-www-form-urlencoded');
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $httpHeader);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1667.0 Safari/537.36');
return $ch;
}
?>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="result"></div>
<script type="module">
addEventListener('DOMContentLoaded', () => {
console.log('ok');
const xhtml = new XMLHttpRequest();
xhtml.onreadystatechange = (res) => {
if ((res.target.status === 201 || res.target.status === 200) && res.target.readyState === 4) {
console.log('----------------res object--------------------' + "<::::>");
console.log(res, "res");
console.log('----------------status--------------------' + "<::::>");
console.log(res.target.status);
console.log('------------------readyState------------------' + "<::::>");
console.log(res.target.readyState);
console.log('------------------response------------------' + "<::::>");
console.log(res.target.response);
console.log('------------------responseText------------------' + "<::::>");
console.log(res.target.responseText);
document.getElementById('result').innerText = res.target.responseText;
}
}
xhtml.open('POST', 'https://reqres.in/api/user');
xhtml.send(JSON.stringify({
url: 'proxy.php?url=https://reqres.in/api/user',
type: 'POST',
data: {name: 'Zlatan Ibrahimovic'},
}));
});
</script>
</body>
</html>
如果您想使用提供的 url 从这一行替换...xhtml.open('POST', 'https://reqres.in/api/user');
const url = JSON.parse(`<?php echo $url?>`);
xhtml.open('POST', url);
xhtml.send(JSON.stringify({
url: 'proxy.php?url=' + url,
type: 'POST',
data: {name: 'Zlatan Ibrahimovic'},
}));
我想出了如何让它发挥作用。 PHP:
<?php
// getting the baseURL from the request
$baseURL = $_REQUEST['url'];
// getting the request method sent in to the proxy
function getRequestMethod() {
return $_SERVER["REQUEST_METHOD"];
}
// getting the POST data from a POST request
function getPostData() {
return http_build_query($_POST);
}
function makeGetRequest($baseURL) {
$ch = curl_init();
$fullURL = $baseURL.<URLparams here>;
curl_setopt($ch, CURLOPT_URL, $fullURL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$response = curl_exec($ch);
curl_close($ch);
if($e = curl_error($ch)) {
echo $e;
} else {
$json = json_decode($response, true);
return print_r($json);
}
}
function makePostRequest($baseURL) {
$ch = curl_init();
$data = http_build_query($_POST);
curl_setopt($ch, CURLOPT_URL, $baseURL);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
if($e = curl_error($ch)) {
echo $e;
} else {
$json = json_decode($response, true);
return print_r($json);
}
}
$response = "";
switch (getRequestMethod()) {
case 'GET':
$response = makeGetRequest($baseURL);
break;
case 'POST':
$response = makePostRequest($baseURL);
break;
default:
echo "There has been an error";
return;
}
echo $response;
JS:
$(document).ready(function () {
$.ajax({
url: 'proxy.php?url=<Endpoint here>',
type: 'POST',
data: {
partnerName: 'applicant',
partnerPassword: 'd7c3119c6cdab02d68d9',
partnerUserID: 'expensifytest@mailinator.com',
partnerUserSecret: 'hire_me',
},
success: function (data) {
console.log(data);
},
});
$.get(
'proxy.php?url=<Endpoint here>',
function (data) {
console.log(data);
}
);
});