Issue
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);
}
}
}
Solution
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: *");
Answered By - M0ns1f
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.