我使用 Slim 创建了一个 GET 函数,它在浏览器中运行良好,即当我点击链接时,但是当我通过 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();
最佳答案
您可以使用选项路由。
//...
$app->options('/:anything+', function () {
$app->response->header("Access-Control-Allow-Origin", "*");
});
//...
关于javascript - angularjs 阻止跨源请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32714289/