Slim Framework v3 api 从 angularjs $http 调用

Slim Framework v3 api call from angularjs $http

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

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

当我从 angularjs $http 调用任何路由时,我得到控制台错误:-

XMLHttpRequest 无法加载 http://192.168.0.5/project/api/testing. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '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();

我已添加 header 作为回应。但是当我从 $http 调用测试路由 api 时仍然会抛出错误。

我一片空白,我知道我只是漏掉了一些愚蠢的东西。请帮我解决这个问题。

谢谢

更新:解决方案

通过在 php 文件中添加 header,它现在可以正常工作了。 header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS'); header('Access-Control-Allow-Headers: Content-Type, Content-Range, Content-Disposition, Content-Description');

请注意这个 link 这几天可能会派上用场:- Click to go->

一件事是第 14 行缺少 return:

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

您可以检查 headers 是否出现在浏览器开发控制台的响应中。

快速回顾一下,这似乎是唯一的问题。