php - CORS 代理 (php) 无法连接到端口
问题描述
当我在浏览器地址栏中向http://fmgold.mvserver.be:4101/7.html发出请求时,我会正确接收元数据。
在我的应用程序中,由于 CORS 问题,对给定路径的请求失败。我无权访问服务器来修改标头,因此我正在尝试使用 PHP 创建 CORS 代理。
<?php
if( ! isset($curl_timeout))
$curl_timeout = 30;
$headers = getallheaders();
$method = __('REQUEST_METHOD', $_SERVER);
$url = $_GET['url'];
// Check that we have a URL
if( ! $url)
http_response_code(400) and exit("Url missing");
foreach($headers as $key => &$value) {
$value = "$key: $value";
}
$curl = curl_init();
do
{
curl_setopt_array($curl, [
CURLOPT_URL => $url,
CURLOPT_PORT => 4101,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_HEADER => TRUE,
CURLOPT_TIMEOUT => $curl_timeout,
CURLOPT_FOLLOWLOCATION => TRUE
]);
// Method specific options
switch($method)
{
case 'HEAD':
curl_setopt($curl, CURLOPT_NOBODY, TRUE);
break;
case 'GET':
break;
case 'PUT':
case 'POST':
case 'DELETE':
default:
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($curl, CURLOPT_POSTFIELDS, file_get_contents('php://input'));
break;
}
// Perform request
ob_start();
curl_exec($curl) or http_response_code(500) and exit(curl_error($curl));
$out = ob_get_clean();
$url = curl_getinfo($curl, CURLINFO_REDIRECT_URL);
}
while($url and --$maxredirs > 0);
$info = curl_getinfo($curl);
curl_close($curl);
// Remove any existing headers
header_remove();
// Use gz, if acceptable
// ob_start('ob_gzhandler');
// Output headers
$header = substr($out, 0, $info['header_size']);
array_map('header', explode("\r\n", $header));
// And finally the body
echo substr($out, $info['header_size']);
// Helper function
function __($key, array $array, $default = null)
{
return array_key_exists($key, $array) ? $array[$key] : $default;
}
我在实时服务器上运行 PHP,但是当我通过代理 php 调用 url 时(http://cors-proxy.myliveserver.com/proxy.php?url=http://fmgold.mvserver.be/7.html
,我收到以下错误响应:
Failed to connect to fmgold.mvserver.be port 4101: Connection refused
将端口添加到 curl 请求似乎没有帮助。任何想法出了什么问题?
解决方案
三件事,
服务器端调用不受 Cross-Origin-Request 策略的约束,除非您在请求中添加“ Origin ”标头
您不需要在 curl 请求中设置端口。
CURLOPT_PORT => 4101,
这不是必需的当您
http://fmgold.mvserver.be:4101/7.html
从浏览器调用此 url 时,不涉及“ Origin ”标头,您可以通过向其发出GET请求来获得响应。但是在服务器端,当您发出请求时,您正在做的是获取服务器标头
$headers = getallheaders();
并将所有这些标头设置在您的 curl 请求中CURLOPT_HTTPHEADER => $headers,
并执行它。我的假设是
$headers
包含“ Origin ”标头,并且主机服务器因此拒绝您使用 CORS 的请求删除它
CURLOPT_HTTPHEADER => $headers,
并尝试。它应该工作
推荐阅读
- javascript - 用于解析开始和结束标签的 Nearley 解析器语法
- javascript - fotorama 画廊在 Swiper 滑块中不起作用
- html - h1 标记中的文本溢出 div 容器
- linux - cx_Oracle 5.3 是否与 Oracle 客户端 19.10 兼容?
- javascript - 如何在 Angular 9 中使用 npm 包的 Highchart 地图集合的 CDN?
- javascript - 错误:使用了无效函数返回值
- reactjs - 无法在代码中找到问题以根据 React 中的用户输入动态分配组件名称
- angular - Syncfusion TreeGrid + Angular 11“错误:必须从注入上下文中调用注入()”
- php - Laravel 如何在两个独立的数据库中创建迁移关系?
- python - 在python中提取Unicode文本