angular send cookies from http request to php - php

so this question ask several time but still i could't figure this out. i'm sending http request from angular app to php service. and i need access the cookies i set from the browser. i know that to access cookies from php service i have to set the withCredentials in my http request. but then again wilcard error raised.
here is the http request
$http({
url : $scope.urlDomain+ "setting/getAll?skip=0&take=10&orderby=asc",
method :"POST",
headers : {
securityToken : "1124"
},
withCredentials: true
})
i had set the headers in my php file
header("Access-Control-Allow-Origin: * ");
header('Access-Control-Allow-Credentials: true');
header("Access-Control-Allow-Methods: PUT,POST, GET, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: origin, x-requested-with, content-type, securityToken");
this is the error
XMLHttpRequest cannot load http://localhost/services/getAll?skip=0&take=10&orderby=asc. Response to preflight request doesn't pass access control check: A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true. Origin 'http://localhost' is therefore not allowed access. The credentials mode of an XMLHttpRequest is controlled by the withCredentials attribute
i stuck in this over day and still could't figure this out. thanks guys

You cant use header("Access-Control-Allow-Origin: * "); when you enable withCredentials, you have to specify a domain like this:
header("Access-Control-Allow-Origin: 127.0.0.1");
header("Access-Control-Allow-Origin: domain2");
header("Access-Control-Allow-Origin: domain3");

Related

EditorJS upload file to php server failes on CORS [duplicate]

So I know there's a lot of CORS posts out there, and I'm just adding to them, but I can't find any with answers that help me out. So I'm building an angular 4 application that relies on my php api. Working locally it's fine, the moment I toss it up on the domain with the app at app.example.com, and the api at api.example.com, I can't get past my login, because I get the following error:
XMLHttpRequest cannot load http://api.example.com/Account/Login.
Response to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://app.example.com' is therefore not allowed
access.
My php code looks like this:
$http_origin = $_SERVER['HTTP_ORIGIN'];
$allowed_domains = array(
'http://example.com',
'https://example.com',
'http://app.example.com',
'https://app.example.com',
'http://www.example.com',
'https://www.example.com'
);
if (in_array(strtolower($http_origin), $allowed_domains))
{
// header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Origin: $http_origin");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400');
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Authorization, Content-Type,Accept, Origin");
exit(0);
}
My Angular post looks like this:
public login(login: Login): Observable<LoginResponse> {
let headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
headers.append('Authorization', 'Basic ' + btoa(login.Username + ':' + login.Password));
return this.http.post(this.apiBaseUrl + '/Account/Login', "grant_type=client_credentials", { headers: headers })
.map(response => {
// code
});
}
If I run the request through postman, which doesn't bother with CORS, I get:
{ "error": "invalid_client", "error_description": "Client credentials were not found in the headers or body" }
I've tried setting origin to '*' just to test and see if that was the core of the issue, and it still fails the same way.
Edit
Just updating from information below. Changing casing in headers had no effect, and pulling the code out of their if statements had no effect.
I debugged the php by telling my live app to go to my local api, and the php is working as expected. It's setting the headers and making it into each of the if statements.
Edit take 2
I could really use some help on this one, if someone has any ideas, I'd really appreciate it.
Edit take 3
If I set all the header stuff in my .htaccess rather than my php, it lets me through. However, now I'm stuck on the error listed above that I always get when using postman, however now it's while using the actual site.
{"error":"invalid_client","error_description":"Client credentials were not found in the headers or body"}
My response headers are like so
Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:authorization, content-type, accept, origin
Access-Control-Allow-Methods:GET, POST, OPTIONS
Access-Control-Allow-Origin:*
I'll be changing it from * to only my domains once I have it working. But for now i'll leave it as *.
My headers as requested.
OK I had a similar issues recently and I solved everything only on the backend side with no .htaccess stuff.
when the browser sends cross server requests it firsts sends an OPTIONS request to make sure it is valid and it can send the "real" request.
After it gets a proper and valid response from OPTIONS, only then it sends the "real" request.
Now for both request on the backend you need to make sure to return the proper headers: content-type, allow-origin, allow-headers etc...
Make sure that in the OPTIONS request on the backend, the app returns the headers and returns the response, not continuing the full flow of the app.
In the "real" request, you should return the proper headers and your regular response body.
example:
//The Response object
$res = $app->response;
$res->headers->set('Content-Type', 'application/json');
$res->headers->set('Access-Control-Allow-Origin', 'http://example.com');
$res->headers->set('Access-Control-Allow-Credentials', 'true');
$res->headers->set('Access-Control-Max-Age', '60');
$res->headers->set('Access-Control-Allow-Headers', 'AccountKey,x-requested-with, Content-Type, origin, authorization, accept, client-security-token, host, date, cookie, cookie2');
$res->headers->set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
if ( ! $req->isOptions()) {
// this continues the normal flow of the app, and will return the proper body
$this->next->call();
} else {
//stops the app, and sends the response
return $res;
}
Things to remember:
if you are using: "Access-Control-Allow-Credentials" = true
make sure that "Access-Control-Allow-Origin" is not "*", it must be set with a proper domain!
( a lot of blood was spilled here :/ )
define the allowed headers you will get in "Access-Control-Allow-Headers"
if you wont define them, the request will fail
if you using "Authorization: Bearer", then "Access-Control-Allow-Headers" should also contain "Authorization", if not, the request will fail
In my similar case with Angular frontend and Php backend helped code below. Firstly I send a headers:
header("Access-Control-Allow-Origin: http://localhost:4200");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST, DELETE, OPTIONS");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
And after them I'm enable ignoring the options request:
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
return 0;
}
This approach helped me handling the "post" and the "delete" embedded request methods from the Angular.
I added below in php and it solved my problem.
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Content-Type, origin");
I had a similar issue,
Dev environment: Apache web server behind NginX Proxy
My app is in a virtual host in my Apache server,
configured with name: appname.devdomain.com
When accessing to web app internaly I wasn´t getting through the proxy:
I was using the url: appname.devdomain.com
I had no problem this way.
But, when accessing it externally using public url: appname.prddomain.com
it would load, even got access to the system after login, then load the templates and some session content, then, if an asynchronous call would be made by the client then I would got the following message in chrome console:
"Access to XMLHttpRequest at 'http://appname.devdomain.com/miAdminPanel.php' from origin 'http://appname.prddomain.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request."
To test this I opened two tabs
1st tab accessed the web using url: appname.devdomain.com, made XMLHttpRequest -> OK
2nd tab accessed the web using url: appname.prddomain.com, made XMLHttpRequest -> CORS error message above.
So, after changing the Nginx proxy configuration:
server {
listen 80;
server_name appname.prddomain.com;
# SSL log files ###
access_log /path/to/acces-log.log;
error_log /path/to/error-log.log;
location / {
proxy_pass http://appname.devdomain.com;
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Server $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
basically this tells the proxy to treat the external request as internal request.

PHP function call inside if statment executed no matter what [duplicate]

So I know there's a lot of CORS posts out there, and I'm just adding to them, but I can't find any with answers that help me out. So I'm building an angular 4 application that relies on my php api. Working locally it's fine, the moment I toss it up on the domain with the app at app.example.com, and the api at api.example.com, I can't get past my login, because I get the following error:
XMLHttpRequest cannot load http://api.example.com/Account/Login.
Response to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://app.example.com' is therefore not allowed
access.
My php code looks like this:
$http_origin = $_SERVER['HTTP_ORIGIN'];
$allowed_domains = array(
'http://example.com',
'https://example.com',
'http://app.example.com',
'https://app.example.com',
'http://www.example.com',
'https://www.example.com'
);
if (in_array(strtolower($http_origin), $allowed_domains))
{
// header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Origin: $http_origin");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400');
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Authorization, Content-Type,Accept, Origin");
exit(0);
}
My Angular post looks like this:
public login(login: Login): Observable<LoginResponse> {
let headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
headers.append('Authorization', 'Basic ' + btoa(login.Username + ':' + login.Password));
return this.http.post(this.apiBaseUrl + '/Account/Login', "grant_type=client_credentials", { headers: headers })
.map(response => {
// code
});
}
If I run the request through postman, which doesn't bother with CORS, I get:
{ "error": "invalid_client", "error_description": "Client credentials were not found in the headers or body" }
I've tried setting origin to '*' just to test and see if that was the core of the issue, and it still fails the same way.
Edit
Just updating from information below. Changing casing in headers had no effect, and pulling the code out of their if statements had no effect.
I debugged the php by telling my live app to go to my local api, and the php is working as expected. It's setting the headers and making it into each of the if statements.
Edit take 2
I could really use some help on this one, if someone has any ideas, I'd really appreciate it.
Edit take 3
If I set all the header stuff in my .htaccess rather than my php, it lets me through. However, now I'm stuck on the error listed above that I always get when using postman, however now it's while using the actual site.
{"error":"invalid_client","error_description":"Client credentials were not found in the headers or body"}
My response headers are like so
Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:authorization, content-type, accept, origin
Access-Control-Allow-Methods:GET, POST, OPTIONS
Access-Control-Allow-Origin:*
I'll be changing it from * to only my domains once I have it working. But for now i'll leave it as *.
My headers as requested.
OK I had a similar issues recently and I solved everything only on the backend side with no .htaccess stuff.
when the browser sends cross server requests it firsts sends an OPTIONS request to make sure it is valid and it can send the "real" request.
After it gets a proper and valid response from OPTIONS, only then it sends the "real" request.
Now for both request on the backend you need to make sure to return the proper headers: content-type, allow-origin, allow-headers etc...
Make sure that in the OPTIONS request on the backend, the app returns the headers and returns the response, not continuing the full flow of the app.
In the "real" request, you should return the proper headers and your regular response body.
example:
//The Response object
$res = $app->response;
$res->headers->set('Content-Type', 'application/json');
$res->headers->set('Access-Control-Allow-Origin', 'http://example.com');
$res->headers->set('Access-Control-Allow-Credentials', 'true');
$res->headers->set('Access-Control-Max-Age', '60');
$res->headers->set('Access-Control-Allow-Headers', 'AccountKey,x-requested-with, Content-Type, origin, authorization, accept, client-security-token, host, date, cookie, cookie2');
$res->headers->set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
if ( ! $req->isOptions()) {
// this continues the normal flow of the app, and will return the proper body
$this->next->call();
} else {
//stops the app, and sends the response
return $res;
}
Things to remember:
if you are using: "Access-Control-Allow-Credentials" = true
make sure that "Access-Control-Allow-Origin" is not "*", it must be set with a proper domain!
( a lot of blood was spilled here :/ )
define the allowed headers you will get in "Access-Control-Allow-Headers"
if you wont define them, the request will fail
if you using "Authorization: Bearer", then "Access-Control-Allow-Headers" should also contain "Authorization", if not, the request will fail
In my similar case with Angular frontend and Php backend helped code below. Firstly I send a headers:
header("Access-Control-Allow-Origin: http://localhost:4200");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST, DELETE, OPTIONS");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
And after them I'm enable ignoring the options request:
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
return 0;
}
This approach helped me handling the "post" and the "delete" embedded request methods from the Angular.
I added below in php and it solved my problem.
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Content-Type, origin");
I had a similar issue,
Dev environment: Apache web server behind NginX Proxy
My app is in a virtual host in my Apache server,
configured with name: appname.devdomain.com
When accessing to web app internaly I wasn´t getting through the proxy:
I was using the url: appname.devdomain.com
I had no problem this way.
But, when accessing it externally using public url: appname.prddomain.com
it would load, even got access to the system after login, then load the templates and some session content, then, if an asynchronous call would be made by the client then I would got the following message in chrome console:
"Access to XMLHttpRequest at 'http://appname.devdomain.com/miAdminPanel.php' from origin 'http://appname.prddomain.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request."
To test this I opened two tabs
1st tab accessed the web using url: appname.devdomain.com, made XMLHttpRequest -> OK
2nd tab accessed the web using url: appname.prddomain.com, made XMLHttpRequest -> CORS error message above.
So, after changing the Nginx proxy configuration:
server {
listen 80;
server_name appname.prddomain.com;
# SSL log files ###
access_log /path/to/acces-log.log;
error_log /path/to/error-log.log;
location / {
proxy_pass http://appname.devdomain.com;
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Server $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
basically this tells the proxy to treat the external request as internal request.

Cors enabled on php file, but still getting error

I'm building an API, for training purposes. I now have to send a POST request containing information. I'm using React JS and PHP, the problem is that everytime I send a request, the CORS error still shows up on the browser.
My JS file that sends the POST is, I changed the URL, because it's on my personal server:
axios.post('https://myurl/api/book/create.php', {
data: JSON.stringify(values, 0, 2)
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
and on the server side, I have the following
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
With postman the request goes smoothly, but every single time sending through the browser
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://myurl/api/book/create.php. (Reason: CORS request did not succeed
Please make sure that you allow CORS in backend server. Then, you need send header for axios like following example
axios.defaults.headers.post['Content-Type'] = 'application/json';
axios.defaults.withCredentials = true;
axios.defaults.crossDomain = true;
(Or setting it in third paramenter after data)
You have to use either localhost or 127.0.0.1 for all the requests. In general in your code you should make calls to the server by just appending the URI to the current host, without re-adding the host and port in the URI string.
Answer based on: CORS request did not succeed

CORS: PHP: Response to preflight request doesn't pass. Am allowing origin

So I know there's a lot of CORS posts out there, and I'm just adding to them, but I can't find any with answers that help me out. So I'm building an angular 4 application that relies on my php api. Working locally it's fine, the moment I toss it up on the domain with the app at app.example.com, and the api at api.example.com, I can't get past my login, because I get the following error:
XMLHttpRequest cannot load http://api.example.com/Account/Login.
Response to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://app.example.com' is therefore not allowed
access.
My php code looks like this:
$http_origin = $_SERVER['HTTP_ORIGIN'];
$allowed_domains = array(
'http://example.com',
'https://example.com',
'http://app.example.com',
'https://app.example.com',
'http://www.example.com',
'https://www.example.com'
);
if (in_array(strtolower($http_origin), $allowed_domains))
{
// header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Origin: $http_origin");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400');
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Authorization, Content-Type,Accept, Origin");
exit(0);
}
My Angular post looks like this:
public login(login: Login): Observable<LoginResponse> {
let headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
headers.append('Authorization', 'Basic ' + btoa(login.Username + ':' + login.Password));
return this.http.post(this.apiBaseUrl + '/Account/Login', "grant_type=client_credentials", { headers: headers })
.map(response => {
// code
});
}
If I run the request through postman, which doesn't bother with CORS, I get:
{ "error": "invalid_client", "error_description": "Client credentials were not found in the headers or body" }
I've tried setting origin to '*' just to test and see if that was the core of the issue, and it still fails the same way.
Edit
Just updating from information below. Changing casing in headers had no effect, and pulling the code out of their if statements had no effect.
I debugged the php by telling my live app to go to my local api, and the php is working as expected. It's setting the headers and making it into each of the if statements.
Edit take 2
I could really use some help on this one, if someone has any ideas, I'd really appreciate it.
Edit take 3
If I set all the header stuff in my .htaccess rather than my php, it lets me through. However, now I'm stuck on the error listed above that I always get when using postman, however now it's while using the actual site.
{"error":"invalid_client","error_description":"Client credentials were not found in the headers or body"}
My response headers are like so
Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:authorization, content-type, accept, origin
Access-Control-Allow-Methods:GET, POST, OPTIONS
Access-Control-Allow-Origin:*
I'll be changing it from * to only my domains once I have it working. But for now i'll leave it as *.
My headers as requested.
OK I had a similar issues recently and I solved everything only on the backend side with no .htaccess stuff.
when the browser sends cross server requests it firsts sends an OPTIONS request to make sure it is valid and it can send the "real" request.
After it gets a proper and valid response from OPTIONS, only then it sends the "real" request.
Now for both request on the backend you need to make sure to return the proper headers: content-type, allow-origin, allow-headers etc...
Make sure that in the OPTIONS request on the backend, the app returns the headers and returns the response, not continuing the full flow of the app.
In the "real" request, you should return the proper headers and your regular response body.
example:
//The Response object
$res = $app->response;
$res->headers->set('Content-Type', 'application/json');
$res->headers->set('Access-Control-Allow-Origin', 'http://example.com');
$res->headers->set('Access-Control-Allow-Credentials', 'true');
$res->headers->set('Access-Control-Max-Age', '60');
$res->headers->set('Access-Control-Allow-Headers', 'AccountKey,x-requested-with, Content-Type, origin, authorization, accept, client-security-token, host, date, cookie, cookie2');
$res->headers->set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
if ( ! $req->isOptions()) {
// this continues the normal flow of the app, and will return the proper body
$this->next->call();
} else {
//stops the app, and sends the response
return $res;
}
Things to remember:
if you are using: "Access-Control-Allow-Credentials" = true
make sure that "Access-Control-Allow-Origin" is not "*", it must be set with a proper domain!
( a lot of blood was spilled here :/ )
define the allowed headers you will get in "Access-Control-Allow-Headers"
if you wont define them, the request will fail
if you using "Authorization: Bearer", then "Access-Control-Allow-Headers" should also contain "Authorization", if not, the request will fail
In my similar case with Angular frontend and Php backend helped code below. Firstly I send a headers:
header("Access-Control-Allow-Origin: http://localhost:4200");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST, DELETE, OPTIONS");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
And after them I'm enable ignoring the options request:
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
return 0;
}
This approach helped me handling the "post" and the "delete" embedded request methods from the Angular.
I added below in php and it solved my problem.
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Content-Type, origin");
I had a similar issue,
Dev environment: Apache web server behind NginX Proxy
My app is in a virtual host in my Apache server,
configured with name: appname.devdomain.com
When accessing to web app internaly I wasn´t getting through the proxy:
I was using the url: appname.devdomain.com
I had no problem this way.
But, when accessing it externally using public url: appname.prddomain.com
it would load, even got access to the system after login, then load the templates and some session content, then, if an asynchronous call would be made by the client then I would got the following message in chrome console:
"Access to XMLHttpRequest at 'http://appname.devdomain.com/miAdminPanel.php' from origin 'http://appname.prddomain.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request."
To test this I opened two tabs
1st tab accessed the web using url: appname.devdomain.com, made XMLHttpRequest -> OK
2nd tab accessed the web using url: appname.prddomain.com, made XMLHttpRequest -> CORS error message above.
So, after changing the Nginx proxy configuration:
server {
listen 80;
server_name appname.prddomain.com;
# SSL log files ###
access_log /path/to/acces-log.log;
error_log /path/to/error-log.log;
location / {
proxy_pass http://appname.devdomain.com;
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Server $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
basically this tells the proxy to treat the external request as internal request.

enabling cors in codeigniter ( restserver by #chriskacerguis )

http.get request in agularJs controller works fine when my client app and api are in localhost.
when api is moved to server., issue arised.
client side using angularJs
$http.get('http://example.com/api/spots/2/0').success(function(data){
console.log(data);
});
log gives:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://example.com/api/spots/2/0. This can be fixed by moving the resource to the same domain or enabling CORS.
i have added these two lines to my controller construct
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET");
still same error.
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");
and return immediately when the request is method 'OPTIONS' once you have set the headers.
if ( "OPTIONS" === $_SERVER['REQUEST_METHOD'] ) {
die();
}
See also this answer.
Angular sends a W3C CORS spec compliant preflight request that will check for the right allowed methods before actually attempting it.
Personally, I find the Mozilla Developer Network CORS page a bit easier to read on the matter to help understand the flow of CORS.
If anyone else is facing the issue, enabling CORS in rest.php file of Codeigniter REST Controller worked for me. This is also clearly documented in comments here https://github.com/chriskacerguis/codeigniter-restserver/blob/master/application/config/rest.php
//Change this to TRUE
$config['check_cors'] = TRUE;
//No change here
$config['allowed_cors_headers'] = [
'Origin',
'X-Requested-With',
'Content-Type',
'Accept',
'Access-Control-Request-Method',
'Authorization',
];
//No change here
$config['allowed_cors_methods'] = [
'GET',
'POST',
'OPTIONS',
'PUT',
'PATCH',
'DELETE'
];
//Set to TRUE to enable Cross-Origin Resource Sharing (CORS) from any source domain
$config['allow_any_cors_domain'] = TRUE;
//Used if $config['check_cors'] is set to TRUE and $config['allow_any_cors_domain'] is set to FALSE.
//Set all the allowable domains within the array
//e.g. $config['allowed_origins'] =['http://www.example.com','https://spa.example.com']
$config['allowed_cors_origins'] = [];
I've added the following constructor in my controller class
public function __construct($config = 'rest')
{
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
parent::__construct();
}
Client side => AngularJs (running with Grunt in localhost:9000)
Server side => php (codeIgniter solution) (running in localhost:80)
The only thing that worked for me was to add this lines into the webservices controller in my php project:
/*
here you do whatever you do to build the $data
*/
//but just before returning the method data add this
header('Content-type: application/json');
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET");
header("Access-Control-Allow-Methods: GET, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Content-Length, Accept-Encoding");
echo json_encode($data, JSON_NUMERIC_CHECK);
Add this to your config.php In order to send the access-control-allow-origin HTTP header to accept connection from everywhere.
$method = $_SERVER["REQUEST_METHOD"];
if ($method == 'OPTIONS') {
header("access-control-allow-origin: *");
die("");
}
if you can use jQuery Ajax, then use this line in your script.
jQuery.support.cors = true; // force cross-site scripting (as of jQuery 1.5)
it solved the problem for me when i tried to post some string using jQuery Ajax from sidebar desktop gadget to the xampp php file.
To add to the answer by #amal-ajith headers should be added in the rest.php file. For example I needed to add my authorization token for Ionic 4 app api calls/requests and all I needed to do was add the header field the rest.php file and my cors error was taken care of.
Access to XMLHttpRequest at 'http://localhost/ci/index.php/api/validate_token' from origin 'http://localhost:8100' has been blocked by CORS policy: Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response.
//No change here
$config['allowed_cors_headers'] = [
'Origin',
'X-Requested-With',
'Content-Type',
'Accept',
'Access-Control-Request-Method',
'Authorization'
];
There a lot of possible solutions here but none of them worked for me.
I did some digging and found something. I'm not gonna explain but I hope it works for you.
Add the following block of code in your controller file .
if (isset($_SERVER['HTTP_ORIGIN'])) {
// Decide if the origin in $_SERVER['HTTP_ORIGIN'] is one
// you want to allow, and if so:
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400'); // cache for 1 day
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
// may also be using PUT, PATCH, HEAD etc
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
exit(0);
}
For me I used curl in one of the route controller. I am using codeignitor 4.
So make a controller naming anything you want.
make a method
use curl in a method:
public function index() { //code using curl or file get contents depending upon your api}
use routes like this: /controller/method in our case index
reference: https://codeigniter4.github.io/userguide/incoming/controllers.html
Add the following code in the parent constructor of your controller
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, OPTIONS, POST, GET, PUT");
header("Access-Control-Allow-Headers: Content-Type, Content-Length, Accept-Encoding");

Categories