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!

All answers to this question, which has the identifier 61079984

The best answer:

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

Last questions

how do i remove the switch on my home screen?
how to edit the JS date and time to update atuomatically?
How to utilize data stored in a multidimensional array
Powermockito not mocking URL constructor in URI.toURL() method
Android Bluetooth LE Scanner only scans when phone's Location is turned on in some devices
docker wordpress container can't connect to mysql container
How can I declare a number in java that is more than 64-bits? [duplicate]
Optaplanner solutionClass entityCollectionProperty should never return null error when simple JSON object passed to controller
Anylogic, get the time a pedestrain is in a queue
How do I fix this syntax issue with my .flex file?
Optimizing query in PHP
How to find the highest number of a column and print two columns of that row in R?
Ideas on “Error: Type com.google.firebase.iid.zzav is referenced as an interface from com.google.firebase.messaging.zzd”?
JCIFS SmbFile.exists() and SmbFile.isDirectory() return false when it exists and I can listFiles()
PHP total order
Laravel booking system design
neural net - undefined column selected
How to indicate y axis does not start from 0 in ggplot?
Fragments in backStack
Spinner how to change the data