【问题标题】:Ionic 5 Get Request to Slim APIIonic 5 获取 Slim API 的请求
【发布时间】:2020-07-19 15:25:26
【问题描述】:

我想从我的 Ionic 应用向使用 Slim 框架构建的 API 发出 get 请求。

这是API的代码:

<?php
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
?>
<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
use Tuupola\Middleware\HttpBasicAuthentication;

require 'vendor/autoload.php';
$jwt_secret = '**************';

$app = new Slim\App;

$app->add(new Tuupola\Middleware\JwtAuthentication([
    "path" => "/api",
    "attribute" => "jwt",
    "secret" => $jwt_secret,  "error" => function ($response, $arguments) {
        $data["status"] = "error";
        $data["message"] = $arguments["message"];
        return $response
            ->withHeader("Content-Type", "application/json")
            ->withHeader("Access-Control-Allow-Origin", "*")
            ->getBody()->write(json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT));
    }
]));

$app->get('/api/hello', function (Request $request, Response $response, array $args) 
{
    $decoded = $request->getAttribute("jwt");
    $response->getBody()->write(json_encode(array("status"=> "200", "message" => "HELLO ".$decoded['uid'] ." - " . $decoded['cus'])));

    return $response;
});

$app->get('/', function (Request $request, Response $response, array $args) {
    $response->getBody()->write(json_encode(array("status"=> "200", "message" => "Welcome to the API")));

    return $response;
});

$app->run();

?>

当我使用邮递员进行测试时,API 工作正常。但是当我尝试在 Ionic 中使用 HTTPClient 调用它时,它不起作用。这是我的离子密码:

import { Component } from '@angular/core';
import { HttpClient, HttpHeaders   } from '@angular/common/http';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})

export class HomePage {

  constructor(private http: HttpClient) 
  {

  }

  sendRequest()
  {
    this.http.get('http://localhost/slim3',).subscribe((data)=>console.log(data));
  }

}

错误消息如下: :8100/home:1 从源 'http://localhost:8100' 对 XMLHttpRequest 的访问已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头。

core.js:6014 ERROR HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: "http://localhost/slim3", ok: false, ...}

我该如何解决?谢谢!

【问题讨论】:

    标签: php angular typescript ionic-framework slim


    【解决方案1】:

    您必须在 Slim 框架中启用 CORS(What is CORS?)。检查http://www.slimframework.com/docs/v3/cookbook/enable-cors.html

    $app-&gt;run(); 之前添加这个(将http://mysite 替换为您的网址,包括端口)

    $app->options('/{routes:.+}', function ($request, $response, $args) {
        return $response;
    });
    
    $app->add(function ($req, $res, $next) {
        $response = $next($req, $res);
        return $response
                ->withHeader('Access-Control-Allow-Origin', 'http://mysite')
                ->withHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Accept, Origin, Authorization')
                ->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS');
    });
    

    【讨论】:

    • 谢谢,但这并不能解决问题。与之前相同的错误消息:/
    • 嗯,我认为这更像是一个离子问题而不是一个纤细的问题。正如我所说,在使用 postman 测试 slim api 时,ecerything 工作正常。
    • 不,这不是离子问题。 Postman 不关心Same-Origin Policy,因为它不是浏览器。 Curl、Insomnia、wget 等也会发生同样的情况。但浏览器会关心。除非您的 API 正确响应任何浏览器(包括 ionic Web 视图)发出的 OPTIONS 请求,否则它将无法正常工作。
    • 好的。我用谷歌搜索了很多,但找不到有效的解决方案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-16
    • 1970-01-01
    • 1970-01-01
    • 2016-01-29
    • 2018-03-04
    相关资源
    最近更新 更多