来自 Angularjs $http的 Slim Framework v3 API 调用


Slim Framework v3 api call from angularjs $http

过去几天我一直在为这个问题而苦苦挣扎。

我在php中使用slim框架v3创建了api。

当我从 AngularJS 调用任何路由时$http我收到控制台错误为:-

XMLHttpRequest 无法加载 http://192.168.0.5/project/api/testing。请求的资源上不存在"访问控制允许源"标头。因此,不允许访问源"http://localhost"。

<?php
use Psr'Http'Message'ServerRequestInterface as Request;
use Psr'Http'Message'ResponseInterface as Response;
require 'vendor/autoload.php';
require 'app/config/configuration.php';
$app = new Slim'App(["settings" => $config]);
spl_autoload_register(function ($class_name) {
require("app/" . $class_name . ".php");
});
$app->get("/testing",function(Request $request,Response $response){
     generateResponse($response,array("message"=>"success"));
});
function generateResponse($response, $data)
{
 return $response->withStatus(200)
    ->withHeader("Content-Type", "application/json")
    ->withHeader("Access-Control-Allow-Origin", "*")
    ->withHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
    ->withHeader("Access-Control-Allow-Headers", "Content-Type, Depth, User-Agent, X-File-Size,X-Requested-With, If-Modified-Since,X-File-Name, Cache-Control, x-hash-key, x-req-timestamp, user-language-pref, Content_Language")
    ->write(json_encode($data));
 }
 $app->run();

我添加了标题作为响应。但是当我从$http调用测试路由 api 时,它仍然会引发错误。

完全空白,我知道我只是错过了一些愚蠢的东西。请帮我解决这个问题。

谢谢

更新:解决方案

通过在 php 文件中添加标头,它现在可以工作了。header('Access-Control-Allow-Origin: *');
header('访问控制-允许-方法:GET, PUT, POST, DELETE, OPTIONS');header('access-control-allow-headers: Content-Type, Content-Range, Content-Disposition, Content-Description');

请注意,此链接在某些日子里可能会很方便:-点击进入>

一件事是第 14 行缺少return

return generateResponse($response,array("message"=>"success"));

您可以在浏览器的开发控制台中检查标头是否存在于响应中。

从快速回顾来看,这似乎是唯一的问题。