0
votes

I have api on localhost (xampp) / codeigniter and im trying to access it via angular 4 and the browser keeps showing this error in the console. api works fine in postman.

[Firefox]:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://lvh.me/ci-abc/api/get_alltasks. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

[Chrome]:

Failed to load http://lvh.me/ci-abc/api/get_alltasks: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.

I have tried changing API url to localhost and 127.0.0.1 as well but didn't work. I am a beginner developer so pardon me if im missing something.

Service function in Angular 4

gettasks()
  {
    return this.http.get('http://lvh.me/ci-abc/api/get_alltasks')
    .map(res=>res.json());
  }

API function in codeigniter

function get_alltasks_get()
    {
        {
            $result = $this->todo_model->get_alltasks();

            if ($result) {
                $this->response($result, 200);
            } else {
                $this->response("No record found", 404);
            }
        }
    }
2

2 Answers

1
votes

It's not Angular problem, the problem caused because you're not in the same domain as your server is, for example, if you try to send a request to example.com from johndoe.com you will get the error and it's browser that blocks the request!

The browser first makes a header request and if the request is allowed, the next request with the real method type will be issued.

For CodeIgniter, try adding OPTIONS to the allowed methods.

header("Access-Control-Allow-Methods: GET, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Content-Length, Accept-Encoding");

Take a look at this answer

0
votes

CORS on PHP

Browsers send specific HTTP headers for cross-site requests initiated from within XMLHttpRequest or the Fetch API. It also expects to see specific HTTP headers sent back with cross-site responses.

An overview of these headers, including sample JavaScript code that initiates requests and processes responses from the server, as well as a discussion of each header, can be found in the HTTP Access Control (CORS) article and should be read as a companion article to this one.

and should be read as a companion article to this one. This article covers processing Access Control Requests and formulating Access Control Responses in PHP.

If you don't have access to configure Apache, you can still send the header from a PHP script. It's a case of adding the following to your PHP scripts:

<?php
header("Access-Control-Allow-Origin: *");