【问题标题】:Slim Framework v3 api call from angularjs $http来自 angularjs $http 的 Slim Framework v3 api 调用
【发布时间】:2016-11-20 00:04:07
【问题描述】:

过去几天我一直在努力解决这个问题。

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

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

XMLHttpRequest 无法加载 http://192.168.0.5/project/api/testing。请求的资源上不存在“Access-Control-Allow-Origin”标头。 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();

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

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

谢谢

更新:解决方案

通过在 php 文件中添加标题,它现在可以工作了。 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');

请注意此链接,它可能会派上用场:- Click to go->

【问题讨论】:

标签: javascript php angularjs slim


【解决方案1】:

一件事是第 14 行缺少return

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

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

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

【讨论】:

  • 在 generateResponse 中返回响应,所以我认为我们不需要再次返回它。我确实在浏览器中检查了标题。当我从浏览器调用 api 时它正在工作,但是当我在 angularjs 中通过 ajax 调用时它不工作
  • 不,你不是。 generateResponse() 返回一个新的 $response 副本,但这个值在 $app->get() 方法的范围内被丢弃,因为它没有存储在任何地方。它在您的浏览器中工作的原因是直接调用时,CORS 不适用。正如我在回答中所写,检查浏览器开发者控制台中的响应标头,您将看不到 Access-Control-Allow-* 或 Content-type 标头。当从另一个域调用 Angular(通常是 AJAX)时,您需要允许 CORS。如果没有我回答中的代码,这不会发生。
  • 是的,你能帮我看看如何在 angularjs 中启用 cors。到目前为止,正如您在我的代码中看到的那样,我已经添加了标题作为响应,所以我认为我不需要对 php 代码做任何额外的事情。
  • 抱歉,它现在可以正常工作 PHP 标头设置错误。
  • 伙计,一切都结束了——你没有从 Slim 发送那些支持 CORS 的标头。您在generateResponse() 中创建的$response 永远不会发送回浏览器,因为您在$app-&gt;get 中丢弃了它。只需按照我的建议在第 14 行添加return,它无需任何额外代码即可工作。
猜你喜欢
  • 1970-01-01
  • 2018-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-01
相关资源
最近更新 更多