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).
Related
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');
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.
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 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.
I'm trying to make a cross domain ajax request i have set the PHP headers on the receiving end and set the jQuery AJAX request but for some reason it works then you refresh the page and it fires a cors origin error with a response code of 503 which from my research its caused by CORS.
I have followed some instructions from here How do I send a cross-domain POST request via JavaScript?
Headers for api.mydomain.co.uk
header('Access-Control-Allow-Origin: https://mydomain.co.uk');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
jQuery for mydomin.co.uk
$.ajax({
type: 'POST',
url: "//api.mydomain.co.uk/application/mp/basket",
crossDomain: true,
xhrFields:{withCredentials: true},
data: {Route: "ItemCount"},
success: function(data) {
$('.count').text(data);
}
});
Browser Response
It turns out that some Plesk installations are a bit buggy and the 503 error comes from the proxy_fcgi apache process.
To temporaraily fix this error you need to set your application in plesk to use FastCGI instead of FPM served by Apache/Nginx.
I once had this issue and I solved by this, I created an .htaccess file in the target website I was trying to access.
<IfModule mod_headers.c>
SetEnvIf Origin "http(s)?://(www\.)?(mydomain)$" AccessControlAllowOrigin=$0$1
Header add Access-Control-Allow-Origin *
</IfModule>
Its an IF condition if the domain which is requesting has mydomain in it then it will allow you to access.
The CORS policy should also specify which headers you can send.
The 503 is a little bit strange. I think you need to set Content-Type in the list of allowed headers, and maybe others. According to MDN these: https://developer.mozilla.org/en-US/docs/Glossary/simple_header are the headers that you don't need to explicitly send
header('Access-Control-Allow-Headers: Content-Type, etc');