【发布时间】: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