Javascript 飞行前响应TinyMCE图像上传时出现CORS 500错误

Javascript 飞行前响应TinyMCE图像上传时出现CORS 500错误,javascript,php,apache,cors,tinymce,Javascript,Php,Apache,Cors,Tinymce,我正在使用TinyMCE并试图上传图像。我的HTML页面由Django提供服务。请参见下面我的图像上传处理程序(由TinyMCE提供) images\u upload\u处理程序:函数(blobInfo、成功、失败、进度){ var-xhr,formData; xhr=newXMLHttpRequest(); //xhr.withCredentials=true; xhr.open('POST','http://localhost/tiny_upload.php'); setRequestHea

我正在使用TinyMCE并试图上传图像。我的HTML页面由Django提供服务。请参见下面我的图像上传处理程序(由TinyMCE提供)

images\u upload\u处理程序:函数(blobInfo、成功、失败、进度){
var-xhr,formData;
xhr=newXMLHttpRequest();
//xhr.withCredentials=true;
xhr.open('POST','http://localhost/tiny_upload.php');
setRequestHeader('x-requested-with','XMLHttpRequest')
xhr.upload.onprogress=函数(e){
进度(e.loaded/e.total*100);
};
xhr.onload=函数(){
var-json;
如果(xhr.status<200 | | xhr.status>=300){
失败('HTTP错误:'+xhr.status);
返回;
}
json=json.parse(xhr.responseText);
如果(!json | | typeof json.location!=“string”){
失败(“无效的JSON:”+xhr.responseText);
返回;
}
成功(json.location);
};
xhr.onerror=函数(){
失败('由于XHR传输错误,图像上载失败。代码:'+XHR.status+
“消息:”+xhr.responseText);
};
formData=新的formData();
append('file',blobInfo.blob(),blobInfo.filename());
xhr.send(formData);
}
下面是我的上传程序php

<?php
error_reporting(E_ERROR | E_WARNING | E_PARSE);
header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']);
/***************************************************
 * Only these origins are allowed to upload images *
 ***************************************************/
$accepted_origins = array("http://localhost", "http://192.168.1.1", "http://127.0.0.1:8000", "http://127.0.0.1");

/*********************************************
 * Change this line to set the upload folder *
 *********************************************/
$imageFolder = "images/";
reset($_FILES);
$temp = current($_FILES);
header('CUS_MSG: hello');
if (is_uploaded_file($temp['tmp_name'])) {
    header('CUS_MSG1: hello');
    if (isset($_SERVER['HTTP_ORIGIN'])) {
        // same-origin requests won't set an origin. If the origin is set, it must be valid.
        if (in_array($_SERVER['HTTP_ORIGIN'], $accepted_origins)) {
            header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']);
        } else {
            header("HTTP/1.1 403 Origin Denied");
            return;
        }
    }

    /*
    If your script needs to receive cookies, set images_upload_credentials : true in
    the configuration and enable the following two headers.
     */
    // header('Access-Control-Allow-Credentials: true');
    // header('P3P: CP="There is no P3P policy."');

    // Sanitize input
    if (preg_match("/([^\w\s\d\-_~,;:\[\]\(\).])|([\.]{2,})/", $temp['name'])) {
        header("HTTP/1.1 400 Invalid file name.");
        return;
    }

    // Verify extension
    if (!in_array(strtolower(pathinfo($temp['name'], PATHINFO_EXTENSION)), array("gif", "jpg", "png"))) {
        header("HTTP/1.1 400 Invalid extension.");
        return;
    }

    // Accept upload if there was no origin, or if it is an accepted origin
    $filetowrite = $imageFolder . $temp['name'];
    move_uploaded_file($temp['tmp_name'], $filetowrite);

    // Respond to the successful upload with JSON.
    // Use a location key to specify the path to the saved image resource.
    // { location : '/your/uploaded/image/file'}
    echo json_encode(array('location' => $filetowrite));
} else {
    // Notify editor that the upload failed
    header("HTTP/1.1 500 Server Error");
}
?>

感谢@Evgeniy在评论中的回复

我将php文件内容更改为以下内容

<?php
error_reporting(E_ERROR | E_WARNING | E_PARSE);
/***************************************************
 * Only these origins are allowed to upload images *
 ***************************************************/
$accepted_origins = array("http://localhost", "http://192.168.1.1", "http://127.0.0.1:8000", "http://127.0.0.1");

/*********************************************
 * Change this line to set the upload folder *
 *********************************************/

$method = $_SERVER['REQUEST_METHOD'];
if ($method == 'OPTIONS') {
    if (isset($_SERVER['HTTP_ORIGIN'])) {
        if (in_array($_SERVER['HTTP_ORIGIN'], $accepted_origins)) {
            header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']);
            header("HTTP/1.1 200 OK");
            return;
        } else {
            header("HTTP/1.1 403 Origin Denied");
            return;
        }
    }
} elseif ($method == 'POST') {
    $imageFolder = "images/";
    reset($_FILES);
    $temp = current($_FILES);
    if (is_uploaded_file($temp['tmp_name'])) {
        header('CUS_MSG1: hello');
        if (isset($_SERVER['HTTP_ORIGIN'])) {
            // same-origin requests won't set an origin. If the origin is set, it must be valid.
            if (in_array($_SERVER['HTTP_ORIGIN'], $accepted_origins)) {
                header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']);
            } else {
                header("HTTP/1.1 403 Origin Denied");
                return;
            }
        }

        /*
    If your script needs to receive cookies, set images_upload_credentials : true in
    the configuration and enable the following two headers.
     */
        // header('Access-Control-Allow-Credentials: true');
        // header('P3P: CP="There is no P3P policy."');

        // Sanitize input
        if (preg_match("/([^\w\s\d\-_~,;:\[\]\(\).])|([\.]{2,})/", $temp['name'])) {
            header("HTTP/1.1 400 Invalid file name.");
            return;
        }

        // Verify extension
        if (!in_array(strtolower(pathinfo($temp['name'], PATHINFO_EXTENSION)), array("gif", "jpg", "png"))) {
            header("HTTP/1.1 400 Invalid extension.");
            return;
        }

        // Accept upload if there was no origin, or if it is an accepted origin
        $filetowrite = $imageFolder . $temp['name'];
        move_uploaded_file($temp['tmp_name'], $filetowrite);

        // Respond to the successful upload with JSON.
        // Use a location key to specify the path to the saved image resource.
        // { location : '/your/uploaded/image/file'}
        echo json_encode(array('location' => 'http://' . $_SERVER['SERVER_NAME'] . '/' . $filetowrite));
    } else {
        // Notify editor that the upload failed
        header("HTTP/1.1 500 Server Error");
    }
} else {
    // Notify editor that the upload failed
    header("HTTP/1.1 500 Server Error");
}
?>

我尝试通过将值设置为*,为Allow header、Allow Methods、Request header、Request Methods添加许多其他头。没有luckinyou
php
-code我只看到了一个脚本返回
500
-code的地方。当函数
上传到\u文件
时会发生这种情况,返回的不是
真值
-值。该功能的具体功能是什么?是否上载文件检查文件是否通过POST提交,我在飞行前请求(请求方法选项)中观察到的一点是,它不发送文件,并且首先希望收到带有CORS头的响应,然后实际的POST请求随文件一起发送。是的,确实如此。首先,ajax发送
选项
-request以确保ajax请求具有发送跨源请求的权限。CORS头发送回
选项请求
,它在您的代码中,但是
选项
没有文件,您的
if
-语句转到返回
500
-代码的
分支。因此,尝试为“选项”-请求指定操作。例如,如果脚本获取“选项”,则使
退出
。@Evgeniy对此非常感谢。我试试看
<?php
error_reporting(E_ERROR | E_WARNING | E_PARSE);
/***************************************************
 * Only these origins are allowed to upload images *
 ***************************************************/
$accepted_origins = array("http://localhost", "http://192.168.1.1", "http://127.0.0.1:8000", "http://127.0.0.1");

/*********************************************
 * Change this line to set the upload folder *
 *********************************************/

$method = $_SERVER['REQUEST_METHOD'];
if ($method == 'OPTIONS') {
    if (isset($_SERVER['HTTP_ORIGIN'])) {
        if (in_array($_SERVER['HTTP_ORIGIN'], $accepted_origins)) {
            header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']);
            header("HTTP/1.1 200 OK");
            return;
        } else {
            header("HTTP/1.1 403 Origin Denied");
            return;
        }
    }
} elseif ($method == 'POST') {
    $imageFolder = "images/";
    reset($_FILES);
    $temp = current($_FILES);
    if (is_uploaded_file($temp['tmp_name'])) {
        header('CUS_MSG1: hello');
        if (isset($_SERVER['HTTP_ORIGIN'])) {
            // same-origin requests won't set an origin. If the origin is set, it must be valid.
            if (in_array($_SERVER['HTTP_ORIGIN'], $accepted_origins)) {
                header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']);
            } else {
                header("HTTP/1.1 403 Origin Denied");
                return;
            }
        }

        /*
    If your script needs to receive cookies, set images_upload_credentials : true in
    the configuration and enable the following two headers.
     */
        // header('Access-Control-Allow-Credentials: true');
        // header('P3P: CP="There is no P3P policy."');

        // Sanitize input
        if (preg_match("/([^\w\s\d\-_~,;:\[\]\(\).])|([\.]{2,})/", $temp['name'])) {
            header("HTTP/1.1 400 Invalid file name.");
            return;
        }

        // Verify extension
        if (!in_array(strtolower(pathinfo($temp['name'], PATHINFO_EXTENSION)), array("gif", "jpg", "png"))) {
            header("HTTP/1.1 400 Invalid extension.");
            return;
        }

        // Accept upload if there was no origin, or if it is an accepted origin
        $filetowrite = $imageFolder . $temp['name'];
        move_uploaded_file($temp['tmp_name'], $filetowrite);

        // Respond to the successful upload with JSON.
        // Use a location key to specify the path to the saved image resource.
        // { location : '/your/uploaded/image/file'}
        echo json_encode(array('location' => 'http://' . $_SERVER['SERVER_NAME'] . '/' . $filetowrite));
    } else {
        // Notify editor that the upload failed
        header("HTTP/1.1 500 Server Error");
    }
} else {
    // Notify editor that the upload failed
    header("HTTP/1.1 500 Server Error");
}
?>