Ionic 5 Get Request to Slim API

1 answer

I would like to make a get request from my Ionic app to an API build with the Slim Framework.

This is the code of the 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();  ?>  

When I'm testing with postman the API works fine. But when I'm trying to call it with the HTTPClient in Ionic, it doesn't work. This is my Ionic Code:

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));   }  } 

The Error message is the following: :8100/home:1 Access to XMLHttpRequest at 'http://localhost/slim3' from origin 'http://localhost:8100' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

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

How can I fix it? Thanks!

Received answer to this question:
The best answer according to the author of the question:

You must enable CORS(What is CORS?) in Slim Framework. Check http://www.slimframework.com/docs/v3/cookbook/enable-cors.html

Add this before $app->run(); (replacing http://mysite by your url, including port)

$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'); });