在 angularjs 中阻止了跨源请求

Cross-Origin Request Blocked in angularjs

我使用 Slim 创建了一个 GET 函数,它在浏览器中运行良好,即当我点击 link 时,但是当我通过 angularjs 调用相同的 url 时,它是显示错误。

 "NetworkError: 404 Not Found - http://www.example.com/folder_name/getSongs/0/10"
  Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://www.example.com/folder_name/getSongs/0/10. (Reason: CORS header 'Access-Control-Allow-Origin' missing).
  Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource. (Reason: CORS request failed).

slim 框架安装在 folder_name 文件夹中

我在slim的index.php中的代码如下

//my db functions file
require_once './common/myfunctions.php';

require 'Slim/Slim.php';
\Slim\Slim::registerAutoloader();

$app = new \Slim\Slim();

$app->get('/getSongs/:minLimit/:maxLimit', function ($minLimit, $maxLimit) use ($app) {

    $response = $app->response();
    $response->header('Access-Control-Allow-Origin', '*');
    $response->header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, DELETE, PUT');
    $response->header('Access-Control-Max-Age', '1000');
    $response->header('Access-Control-Allow-Headers', 'x-requested-with, Content-Type, origin, authorization, accept, client-security-token');

    $response_array = array(); //response will be send

    $songList = getSongsList($minLimit, $maxLimit);

    if (isset($songList) && !empty($songList)) {

        foreach ($songList as $key => $value) {
            $response_array['data'][$key] = $value;
        }
        $response_array['success'] = TRUE;

        $app->status(200); //Ok
    }
    //blank array
    else {
        $response_array = array("success" => TRUE, "data" => NULL);
        $app->status(204); //No Content
    }

    echo json_encode($response_array);
});

$app->run();

这是一个 CORS 问题,在您的 PHP 文件顶部添加

header("Access-Control-Allow-Origin: *");

您还可以指定它应该允许的 IP 地址列表,而不是 *

在此处了解更多信息 https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

您可以使用选项路线。

//...

$app->options('/:anything+', function  () {
    $app->response->header("Access-Control-Allow-Origin", "*");
});

//...