是否可以在PHP CLI 服务器中启用 CORS (如果可以,如何启用)?
编辑:要解决诸如我应该只在脚本中包含标题的注释,请注意,我的代码中没有任何 PHP 文件/脚本。我只是将 PHP CLI 服务器用作轻量级本地托管选项。因此,理想情况下,答案将提供 CLI 选项,或者表明没有。
使用 php 路由脚本在 webhook 文件夹中使用 DocumentRoot 启动服务器:
php -S localhost:8888 -t webhook webhook/dev-routings.php
Run Code Online (Sandbox Code Playgroud)
webhook/dev-routings.php :
<?php
// Copyright Monwoo 2017, service@monwoo.com
// Enabling CORS in bultin dev to test locally with multiples servers
// used to replace lack of .htaccess support inside php builting webserver.
// call with :
// php -S localhost:8888 -t webhook webhook/dev-routings.php
$CORS_ORIGIN_ALLOWED = "http://localhost:3000";
function consoleLog($level, $msg) {
file_put_contents("php://stdout", "[" . $level . "] " . $msg . "\n");
}
function applyCorsHeaders() {
global $CORS_ORIGIN_ALLOWED;
header("Access-Control-Allow-Origin: {$CORS_ORIGIN_ALLOWED}");
header("Access-Control-Allow-Credentials: true");
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Accept');
}
if (preg_match('/\.(?:png|jpg|jpeg|gif|csv)$/', $_SERVER["REQUEST_URI"])) {
consoleLog('info', "Transparent routing for : " . $_SERVER["REQUEST_URI"]);
return false;
} else if (preg_match('/^.*$/i', $_SERVER["REQUEST_URI"])) {
$filePath = "{$_SERVER['DOCUMENT_ROOT']}/{$_SERVER["REQUEST_URI"]}";
applyCorsHeaders();
if (!file_exists($filePath)) {
consoleLog('info', "File not found Error for : " . $_SERVER["REQUEST_URI"]);
// return false;
http_response_code(404);
echo "File not Found : {$filePath}";
return true;
}
$mime = mime_content_type($filePath);
// /sf/ask/3162553621/
// /sf/ask/506533401/
// Otherwise, you can use custom rules :
$customMappings = [
'js' => 'text/javascript', //'application/javascript',
'css' => 'text/css',
];
$ext = pathinfo($filePath, PATHINFO_EXTENSION);
// consoleLog('Debug', $ext);
if (array_key_exists($ext, $customMappings)) {
$mime = $customMappings[$ext];
}
consoleLog('info', "CORS {$CORS_ALLOWED} added to file {$mime} : {$filePath}");
header("Content-type: {$mime}");
echo file_get_contents($filePath);
return true;
} else {
consoleLog('info', "Not catched by routing, Transparent serving for : "
. $_SERVER["REQUEST_URI"]);
return false; // Let php bultin server serve
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5158 次 |
| 最近记录: |