CORS policy: No 'Access-Control-Allow-Origin' from same server - php

I have a problem with CORS policy. Trying access to php file in the same server of ajax code, but have the CORS error.
await $.ajax({
url: '/includes/paystripe.php',
type: 'POST',
crossDomain: true,
data: {api_key_stripe: api_key_stripe, customer_id:customer_id},
success: function(data){
}
});
Error:
Access to XMLHttpRequest at 'https://www.subDomain.domain.com/includes/paystripe.php' (redirected from 'https://subDomain.domain.com/includes/paystripe.php') from origin 'https://subDomain.domain.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
If I work on localhost, don't have this problem, it's posible poblem with server config?
EDIT:
If I put headers on paystripe.php get a 500 error (only on server, not on localhost):
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');

Related

CORS error in PHP server, even though 'header('Access-Control-Allow-Origin: *')' is present

I got a simple PHP server running on my local. I send requests from frontend to the PHP server. But I get CORS error even though 'header('Access-Control-Allow-Origin: *')' is present on the PHP file.
Frontend runs on 8080 port and PHP server runs on 3000 port.
Here is the error I get
Access to XMLHttpRequest at 'http://localhost:3000/' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
And these lines are at the top of the PHP file
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Credentials: true");
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token , Authorization');
Any idea why?

Response to preflight request - can't see why? (CORS, fetch, PHP)

I found many discussions online about this, e.g. such as this great accepted answer, but still can't work out what's wrong. I've done the following:
Created a React app using create-react-app.
Started the server using npm start and can see my app in the browser.
Using fetch to contact my local server:
fetch("http://xxx.xxx.xxx.xxx/endpoint.php", {
method: "post",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify({
name: credentials.username,
password: credentials.password
})
}).then(response => {
console.log("fetch competed!");
});
In my PHP endpoint,
<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: X-Requested-With, Content-Type, Origin, Cache-Control, Pragma, Authorization, Accept, Accept-Encoding");
header("Access-Control-Allow-Methods: PUT, POST, GET, OPTIONS, DELETE");
...
But then Chrome console debug says:
Access to fetch at 'http://localhost:3000/endpoint.php' from origin 'http://xxx.xxx.xxx.xxx:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Having done some reading, the preflight request sends an OPTIONS to the server, which I have allowed in the PHP header. I also tried some proxies in the package.json file and restarted the server using npm start.
I also tried passing through https://cors-anywhere.herokuapp.com/ and I still get an error:
Access to fetch at 'http://xxx.xxx.xxx.xxx:3000/php/login.php' (redirected from 'https://cors-anywhere.herokuapp.com/http://xxx.xxx.xxx.xxx:3000/php/login.php') from origin 'http://xxx.xxx.xxx.xxx:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
I also tried replacing my fetch with something simpler:
fetch(url, {
method: "POST",
body: new URLSearchParams("email=test#example.com&password=pw")
});
but still it does not work.
I don't understand what the problem could be?
For those facing similar problems, I managed to fix this issue by starting a separate Apache server, systemctl start apache, and hosting my PHP endpoints in the Apache root, e.g. /var/www/html/public/. For some reason the create-react-app development server just wouldn't work, but hosting my files on a separate local server worked fine.

React + Codeigniter Response for preflight is invalid

I have a website that was built using codeigniter MVC but following modern trends I'm trying to create a frontend based on react. I still want to use original codeigniter framework and controllers but instead or rendering views I want it to return plain JSON. Currently I'm stuck on being unable to send requests from react application that runs in debug mode on localhost:3000 to my codeigniter api that is running on apache http://mywebsite:80
this is how I'm initiating request:
fetch("http://mywebsite/Api" + route + '/', {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
method: "POST",
redirect: 'follow',
body: JSON.stringify(data),
dataType : 'json'
})
This is the error I'm getting in a console:
Failed to load http://mywebsite/ApiAuth/login/: Response for preflight
is invalid (redirect)
My php page sends the following back:
header('Content-Type: application/json;charset=UTF-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: DELETE, HEAD, GET, OPTIONS, POST, PUT');
header('Access-Control-Allow-Headers: Content-Type, Content-Range, Content-Disposition, Content-Description');
header('Access-Control-Max-Age: 1728000');
Console outputs:
Request URL: http://mywebsite/ApiAuth/login/
Request Method: OPTIONS
Status Code: 302 Found
Remote Address: [::1]:80
Referrer Policy: no-referrer-when-downgrade
Was able to fix the issue by setting Apache response headers and redirect method like this:
#Redirect for CORS Preflight request
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule ^(.*)$ $1 [R=200,L]
#Set headers to access CORS Requests / allowing localhost only
Header always add Access-Control-Allow-Origin "*"
Header always add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header always add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"

Laravel 5.6 DELETE and PUT 403 access forbidden

Laravel version: 5.6
PHP version: 7.1
I finished my project and tested it locally. But when I uploaded it on a shared hosting site, I get two errors (I'm not sure if they're two separate errors):
DELETE http://SomeAddress/patients/440627036 403 (Forbidden)
Failed to load http://SomeAddress/patients/440627036: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://SomeAddress' is therefore not allowed access. The response had HTTP status code 403.
It was CORS issue which I think I fixed. I was getting CORS error for only PUT and DELETE (I don't know why POST and GET were working!). I added the required headers and this error went away.These are the headers I added:
return $next($request)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE, OPTIONS')
->header('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With')
->header('Access-Control-Allow-Credentials', 'true')
->header('Access-Control-Max-Age', '10000');
But now I get another error (again only happens for PUT and DELETE) - (Is it related to Laravel or my shared hosting site or my backend code?):
Forbidden
You don't have permission to access /patients/440627035 on this server.
Has my CORS issue been solved completely? How can I fix these errors?
Frontend (I use AngularJS $resource to send my HTTP requests):
this.patientRes = function () {
return $resource(baseURL + 'patients/:id', {id: "#id"}, {
get: {
method: 'GET',
isArray: true,
headers: {'Content-Type': 'application/json'}
},
update: {
method: 'PUT',
headers: {'Content-Type': 'application/json'}
},
delete: {
method: 'DELETE',
headers: {'Content-Type': 'application/json'}
}
})
};
Update:
My file structure was like this:
public_html/public/ and my files were here
I change it to:
public_html/ and my files are now here
Now I get this error:
Use this package:
CORS Middleware for Laravel 5
In above Link given installation step also.

CORS Error on Same Domain

This is a segment of my ajax request
$.ajax({
url: url,
type:"POST",
crossDomain:true,
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
The url points to a controller, everything is on the same domain.
I am using codeigniter, I have these headers set in both my controller and htaccess
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: X-Requested-With, content-type, X-Token, x-token');
I have read all the solutions on these links
Making get request for same domain giving CORS error
CORS error on same domain?
and others but still not working. Please any suggestion?
This is the error
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at "the link". (Reason: missing token ‘access-control-allow-headers’ in CORS header ‘Access-Control-Allow-Headers’ from CORS preflight channel).

Categories