header(‘Access-Control-Allow-Origin: *’); Not allowing CORS request
I have a PHP file which generates a JSON document. I’ve set the header as follows but am still getting an error.
header('Access-Control-Allow-Origin: *'); header('Content-Type: application/json');
Error message: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘https://mysubdomain.mydomain.com’ is therefore not allowed access. I’ve tried explictly allowing mysubdomain.mydomain.com using
header('Access-Control-Allow-Origin: https://mysubdomain.mydomain.com');
Are you getting the header in your Chrome’s web inspector’s network tab when you make the request? Or using the curl command line?
Thanks, by using curl from the command line I was able to diagnose the issue. It was actually an error in the PHP code later on that was causing the problems.
You’re welcome. Always remember to check and debug output first :). I have posted my comment as an answer so that you can accept it and close this question.
3 Answers 3
It doesn’t look there is anything wrong with the code that sets the header, but you may want to check if the header is actually being set. Use curl -i http://yourapp to check the response headers being sent to debug it. Alternatively, you can use the network tab in Google Chrome’s web inspector, or the Network tool in Firefox’s Web Developer tools.
I am facing the same issue. Did not get anything useful in the Network tool. However, it shows Access-Control-Allow-Origin: * while making curl call
with htaccess file you can try to set :
Header always set Access-Control-Allow-Methods "POST, GET, PUT, OPTIONS, PATCH,DELETE" Header always set Access-Control-Allow-Origin "*" Header always set Access-Control-Allow-Credentials "true" Header always set Access-Control-Allow-Headers "content-type,Authorization,Cache-Control,X-Requested-With, X-XSRF-TOKEN"
header('Access-Control-Allow-Origin: *'); header('Access-Control-Allow-Methods: POST, GET, PUT, OPTIONS, PATCH, DELETE'); header('Access-Control-Allow-Credentials: true'); header('Access-Control-Allow-Headers: Authorization, Content-Type, x-xsrf-token, x_csrftoken, Cache-Control, X-Requested-With');
Как указать Access-Control-Allow-Origin в php?
CORS защищает от запроса не со стороннего сайта (сервера), а со стороннего клиента (браузера).
С помощью CORS мы даем команду «проверь, что ajax запрос был запущен со страницы, которую мы отправили клиенту», т.к. заголовок origin при ajax запросе будет равен домену, на странице которого находился браузер, когда запрос делал. Этот origin в итоге и проверяется на соответствие разрешенному.
То есть он защищает от того, чтобы кто-то на своем сайте не разместил javascript код, который запрашивает данные напрямую с вашего сайта и показывает их на том сайте, как будто данные принадлежали не вам, а другому сайту.
Если вы хотите запретить запрос с другого сайта (сервера), это сделать геморойно и простейшая для реализации защита — это капча на случай если другой сервер делает слишком много запросов = условная проверка IP адреса, который сервер отсылает (но его можно подменить используя прокси, поэтому читай дальше)
Либо это набор букв-цифр (хеш), который ваш же сервер при первом запросе выдает другому серверу позволяя в дальнейшем делать запросы только дублируя выданное вами значение. По сравнению с проверкой IP это дает каждому клиенту свой собственный хеш, тогда как проверка IP может дать неожиданный результат, если люди сидят в компьютерном клубе и 10 человек будут считаться одним.
Первый раз без проверки и отсылается клиенту хеш, а все запросы логики можно сделать потом только если тот сервер передает вам поле, которое вы ему давали (да, это CSRF называется, правда под ним чаще понимают только защиту форм, но принцип именно такой, и можно не только формы проверять, а вообще любые запросы)
После чего по этому полю ведется какой-нибудь подсчет суммы запросов, и если сумма выше N — показ капчи или просто ошибку отдаем вместо данных, это позволяет в некоторой степени быть уверенным, что запрос не делается автоматически и много раз, защищает от DDOS (но тоже частично, т.к. всегда можно сделать запрос с десятка разных компьютеров, все они получат хеш и каждый из них сделает по пару запросов, чтобы не вызвать капчу).
Полная защита может быть так сделана — все запросы логики разрешены только аяксом и стоят корсы, что только с вашего сайта. А все не-ajax и не-GET запросы проверяются на список разрешенных IP адресов. Но даже тут заголовки можно сгенерировать так «как будто это ajax запрос» и все равно пробить.
How do I enable cross-origin resource sharing on XAMPP?
I have a html file on my localhost with a form and jquery/ajax which handles the post data. A simple php script looks up the data in a mysql database table This is the main part:
// $.post('lookup_update.php', $(this).serialize()) //
XMLHttpRequest cannot load http://www.example.com/projectX/lookup_update.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. The response had HTTP status code 404.
header("Access-Control-Allow-Origin: *");
for php. But when I add this to example.com/lookup_update.php, the file gives a 404 when the localhost file tries to call it. I also tried to add the following to my Xampp apache config file
Header set Access-Control-Allow-Origin "*"
How do I correctly enable cross-origin resource from my local XAMPP setup?? [EDIT] This is my simple form on my localhost
[EDIT 2] OK, i don't think it has to do with the online lookup_update.php file, as I am using this to test in another file var testXHR = $.post("http://www.example.com/projectX/lookup_update.php", function (data) < alert("success:" + data); >)
URLs in the question are rather confusing. Is it http://www.example.com/projectX/lookup_update.php example.com/lookup_update.php , or http://www.example.com/projectX/index.php ?
@AlexBlex I meant the same file I rename index.php to lookup_update.php. It is this file that is online and which I like to call locally
Could you update the question with correct file names, a snippet of the code where you add header , and output of the command curl -v http://www.example.com/_correct_url_here -o /dev/null
4 Answers 4
If you want to allow CORS in the httpd.conf file this is what worked for me:
Header set Access-Control-Allow-Origin "*" Header set Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS" Header set Access-Control-Allow-Headers "X-Requested-With, Content-Type, X-Token-Auth, Authorization"
Put it below the Listen 80 line in the httpd.conf file.
When I used only Header set Access-Control-Allow-Origin "*" , GET requests worked, but POST didn't.
The enviroment it was tested is Windows 10 on Apache server using XAMPP. Apache is hosting a Laravel project.
You have to write below code at the beginning of your lookup_update.php
header('Access-Control-Allow-Origin: *'); header('Content-type: application/json');
Instead of * you can write just Ip address.
First you have to check where is problem either on localhost or other server.
Try this code : If you getting some data in alert then problem is on localhost else on other server.
$.post( "test.php", function( data ) < alert( "Data Loaded: " + data ); >);
sounds promising, but as I am calling from my localhost should I use the IP address of my current location? I mean when I take my computer to another place I get another IP addresss, correct? Oh btw what suprises me is when I google "my current ip" I get 2001:980:cb55:1:xxx:xxxx::25c9 is this IP per computer and can I use this one as well? OH, leaving under a rock this is IPv6 and not good old xxx.xxx.xxx.xx.
If you are getting data from different server then you can use IP address. On localhost there is not need.
I tried header("Access-Control-Allow-Origin: 2001:980:xxxx:1:ec29:xxxx:fe4c:25c9"); at the beginning of my example.com/projectX/lookup_update.php but still I get the warning
First let me clear one thing. you are calling ajax from localhost and getting response from different server(not localhost) ?
yes ajax call is from localhost $.post('http://www.example.com/projectX/lookup_update.php', $(this).serialize()) .done(function (data) and online lookup_update.php echo json format data
CORS requests are "secured" with preflight requests.
Additionally, for HTTP request methods that can cause side-effects on user data (in particular, for HTTP methods other than GET, or for POST usage with certain MIME types), the specification mandates that browsers "preflight" the request, soliciting supported methods from the server with an HTTP OPTIONS request method, and then, upon "approval" from the server, sending the actual request with the actual HTTP request method
This is just a guess here, but you are probably using a framework, and you forgot to enable (implement) OPTIONS route for your requests.
Worth noting, you shouldn't use the wildcard header ( allowing any site to CORS your service ), you should rather specify a whitelist.
Another header that you should be sending is allowed request method.
Access-Control-Request-Method: POST
Кроссдоменные запросы (CORS) простая реализация
Несколько раз у меня уже возникала мысль о реализации кроссдоменных запросов между своими сервисами, однако толково настроить получалось плохо. Давайте уже наконец-то разберемся в этой теме.
Для начала, рассмотрим пример:
У вас есть сайт «А», на пример, реализованный на Laravel и vue.js, который реализует определенную логику работы с какими-либо данными. Сейчас вы, в рамках одного сервиса (в данном случае, несколько микро сервисов решающих разные задачи для одного большого проекта), создаете сайт «Б», которому необходимо работать с той же базой данных и использовать часть функционала сайта «А».
Как решить этот вопрос? Естественно вы можете повторно реализовать необходимый функционал на сайте «Б» и подключиться к базе сайта «А». Но в этом есть свои существенные минусы, как минимум это:
- Вы, в рамках одной системы, дублируете код, который вы написали ранее.
- Вы используете прямой доступ к БД из двух разных мест, это существенно усложнит поиск ошибок, если такие возникнут и такой подход считается далеко не «лучшей практикой».
Так же, у вас есть ещё один вариант реализации (да, это первое, что пришло вам в голову) — jsonp. Но особенности этого метода заключаются в некоторой сложности реализации:
- Высокие требования к безопасности данного подхода
- Требования к изменению кода уже написанного ранее для сайта «А».
- Метод позволят только получить данные, если вам, к примеру требуется отправить информацию методом POST, при помощи jsonp вы этого сделать не сможете.
- Уязвимость к инъекциям — вы должны полностью доверять серверу, от которого получаете данные, ведь вы будете выполнять весь код, который вам от него приходит.
Но есть вариант лучше, проще, так как не требует внесения изменений на сайте «А» и является более безопасным подходом, это кроссдоменные запросы или CORS — Cross-origin resource sharing (в переводе: совместное использование ресурсов между разными источниками).
Суть метода очень проста: для того, чтобы серверу «А» получить или отправить данные на сервер «Б», достаточно на сервере «Б» установить «разрешение» на получение и ответ на запросы с сервера «А». Делается это следующим образом: в заголовках ответа на сервере «Б» вам необходимо установить следующие записи: