Ошибка cors localhost

I am stuck with this CORS problem, even though I set the server (nginx/node.js) with the appropriate headers.

I can see in Chrome Network pane -> Response Headers:

Access-Control-Allow-Origin:http://localhost

which should do the trick.

Here’s the code that I now use to test:

var xhr = new XMLHttpRequest();
xhr.onload = function() {
   console.log('xhr loaded');
};
xhr.open('GET', 'http://stackoverflow.com/');
xhr.send();

I get

XMLHttpRequest cannot load http://stackoverflow.com/. Origin http://localhost is not allowed by Access-Control-Allow-Origin.

I suspect it’s a problem in the client script and not server configuration…

Liam's user avatar

Liam

27.2k28 gold badges125 silver badges187 bronze badges

asked Jun 4, 2012 at 14:42

whadar's user avatar

7

Chrome does not support localhost for CORS requests (a bug opened in 2010, marked WontFix in 2014).

To get around this you can use a domain like localho.st (which points at 127.0.0.1 just like localhost) or start chrome with the --disable-web-security flag (assuming you’re just testing).

answered Jun 5, 2012 at 6:06

Beau's user avatar

BeauBeau

11.2k8 gold badges44 silver badges37 bronze badges

17

Per @Beau’s answer, Chrome does not support localhost CORS requests, and there is unlikely any change in this direction.

I use the Allow-Control-Allow-Origin: * Chrome Extension to go around this issue. The extension will add the necessary HTTP Headers for CORS:

Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: "GET, PUT, POST, DELETE, HEAD, OPTIONS"
Access-Control-Expose-Headers: <you can add values here>

The source code is published on Github.

Note that the extension filter all URLs by default. This may break some websites (for example: Dropbox). I have changed it to filter only localhost URLs with the following URL filter

*://localhost:*/*

Jonathan Arbely's user avatar

answered Sep 30, 2017 at 17:58

Hanxue's user avatar

HanxueHanxue

12.1k18 gold badges87 silver badges129 bronze badges

9

None of the extensions worked for me, so I installed a simple local proxy. In my case https://www.npmjs.com/package/local-cors-proxy
It is a 2-minute setup:

(from their site)

npm install -g local-cors-proxy

API endpoint that we want to request that has CORS issues:
https://www.yourdomain.ie/movies/list

Start Proxy: lcp --proxyUrl https://www.yourdomain.ie

Then in your client code, new API endpoint:
http://localhost:8010/proxy/movies/list

Worked like a charm for me: your app calls the proxy, who calls the server. Zero CORS problems.

answered Apr 22, 2020 at 18:58

daniel p's user avatar

daniel pdaniel p

6617 silver badges12 bronze badges

3

The real problem is that if we set -Allow- for all request (OPTIONS & POST), Chrome will cancel it.
The following code works for me with POST to LocalHost with Chrome

<?php
if (isset($_SERVER['HTTP_ORIGIN'])) {
    //header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
    header("Access-Control-Allow-Origin: *");
    header('Access-Control-Allow-Credentials: true');    
    header("Access-Control-Allow-Methods: GET, POST, OPTIONS"); 
}   
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
        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);
} 
?>

Yves M.'s user avatar

Yves M.

29.6k23 gold badges106 silver badges143 bronze badges

answered Jun 15, 2013 at 16:11

greensuisse's user avatar

greensuissegreensuisse

1,69916 silver badges18 bronze badges

1

Chrome will make requests with CORS from a localhost origin just fine. This isn’t a problem with Chrome.

The reason you can’t load http://stackoverflow.com is that the Access-Control-Allow-Origin headers weren’t allowing your localhost origin.

answered Sep 15, 2019 at 5:06

Brad's user avatar

BradBrad

158k53 gold badges342 silver badges526 bronze badges

1

Agreed! CORS should be enabled on the server-side to resolve the issue ground up. However…

For me the case was:

I desperately wanted to test my front-end(React/Angular/VUE) code locally with the REST API provided by the client with no access to the server config.

Just for testing

After trying all the steps above that didn’t work I was forced to disable web security and site isolation trials on chrome along with specifying the user data directory(tried skipping this, didn’t work).

For Windows

cd C:Program FilesGoogleChromeApplication

Disable web security and site isolation trials

chrome.exe  --disable-site-isolation-trials --disable-web-security --user-data-dir="PATH_TO_PROJECT_DIRECTORY"

This finally worked! Hope this helps!

answered Nov 17, 2020 at 17:17

Aditya Patnaik's user avatar

4

Chrome does allow CORS on localhost, I made it work with AWS API gateway/lambda. Viewing the network tab in the developer tools when sending http requests was very helpful. My problem was that my lambda function was not dealing with the preflight OPTIONS request, only POST and GET. I solved the issue by accepting OPTIONS requests and making sure to return the following headers from my API:

  • Access-Control-Allow-Origin: ‘*’ (or website domain)
  • Access-Control-Allow-Methods: ‘POST, GET, OPTIONS’
    • this is the preflight response telling chrome that we can now send a POST/GET request
  • Access-Control-Allow-Headers: ‘Content-Type’
    • not sure if this is necessary, but it tells chrome that the request can include a Content-Type header

The important thing to note is that the browser sends 2 sets of headers.

  1. OPTIONS headers which includes
    • access-control-request-method: ‘POST’ (or whatever http method you are requesting)
    • origin: ‘http://localhost:3000’ (website domain)
    • referer: ‘http://localhost:3000/’ (I believe this is the full website path)
    • sec-fetch-mode: ‘cors’
    • sec-fetch-site: ‘cross-site’

if the response to request 1 is 200 code and the response header contains:
‘access-control-allow-methods’: ‘POST’ (or whatever the access-control-request-method was in the request),

  1. Actual request, for example: POST headers which includes
    • content-type: ‘application/json’
    • origin: same as above
    • referer: same as above

There are more headers but I think these were the most important.

answered Jun 19, 2021 at 18:44

Matthew P's user avatar

Matthew PMatthew P

1131 silver badge8 bronze badges

Quick and dirty Chrome extension fix:

Moesif Orign & CORS Changer

However, Chrome does support cross-origin requests from localhost. Make sure to add a header for Access-Control-Allow-Origin for localhost.

answered Nov 20, 2019 at 19:58

kaleazy's user avatar

kaleazykaleazy

5,8622 gold badges46 silver badges51 bronze badges

1

I think my solution to this might be the simplest. On my development machine, I added a fake domain in my hosts file similar to http://myfakedomain.notarealtld and set it to 127.0.0.1. Then I changed my server’s CORS configuration (in my case an S3 bucket) to allow that domain. That way I can use Chrome on localhost and it works great.

Make sure your CORS configuration takes into account the entire hostname with port, ie. http://myfakedomain.notarealtld:3000

You can modify your hosts file easily on Linux, Mac, and Windows.

answered Nov 27, 2020 at 22:34

DustinA's user avatar

DustinADustinA

4895 silver badges9 bronze badges

I decided not to touch headers and make a redirect on the server side instead and it woks like a charm.

The example below is for the current version of Angular (currently 9) and probably any other framework using webpacks DevServer. But I think the same principle will work on other backends.

So I use the following configuration in the file proxy.conf.json:

{
  "/api": {
    "target": "http://localhost:3000",
    "pathRewrite": {"^/api" : ""},
   "secure": false
 }
}

In case of Angular I serve with that configuration:

$ ng serve -o --proxy-config=proxy.conf.json

I prefer to use the proxy in the serve command, but you may also put this configuration to angular.json like this:

"architect": {
  "serve": {
    "builder": "@angular-devkit/build-angular:dev-server",
    "options": {
      "browserTarget": "your-application-name:build",
      "proxyConfig": "src/proxy.conf.json"
    },

See also:

https://www.techiediaries.com/fix-cors-with-angular-cli-proxy-configuration/

https://webpack.js.org/configuration/dev-server/#devserverproxy

Community's user avatar

answered Mar 16, 2020 at 22:50

Juri Sinitson's user avatar

Juri SinitsonJuri Sinitson

1,3951 gold badge12 silver badges18 bronze badges

Время на прочтение
8 мин

Количество просмотров 23K

В этой статье мы с вами разберемся, что такое CORS, CORS-ошибки и из-за чего мы можем с ними сталкиваться. Я также продемонстрирую возможные решения и объясню, что такое предварительные (preflight) запросы, CORS-заголовки и в чем заключается их важность при обмене данными между сторонами. Эта статья рассчитана на тех, у кого уже есть базовые познания в области веб-разработки и некоторый опыт с протоколом HTTP. Я старался писать статью так, чтобы она была понятна и новичкам, будучи наполненной знаниями, но при этом стараясь избегать слишком большого количества технических нюансов, не связанных с темой CORS. Если вы заметите какие-либо ошибки или у вас будут предложения, не стесняйтесь писать мне. В некоторых местах я нарочно делал упрощения, говоря “служба”, подразумевая “сервер”, и наоборот.

Что такое CORS?

Cross-Origin Resource Sharing (CORS или “совместное использование ресурсов различными источниками”) — это контролируемый и применяемый в принудительном порядке клиентом (браузером) механизм обеспечения безопасности на основе HTTP. Он позволяет службе (API) указывать любой источник (origin), помимо себя, из которого клиент может запрашивать ресурсы. Он был разработан в соответствии с same-origin policy (SOP или “политика одинакового источника”), которая ограничивает взаимодействие сайта (HTML-документа или JS-скрипта), загруженного из одного источника, с ресурсом из другого источника. CORS используется для явного разрешения определенных cross-origin запросов и отклонения всех остальных.

В основном CORS реализуют веб-браузеры, но как вариант его также можно использовать в API-клиентах. Он присутствует во всех популярных браузерах, таких как Google Chrome, Firefox, Opera и Safari. Этот стандарт был принят в качестве рекомендации W3C в январе 2014 года. Исходя из этого, можно смело предполагать, что он реализован во всех доступных в настоящее время браузерах, которые не были перечислены выше.

Как это работает?

Все начинается на стороне клиента, еще до отправки основного запроса. Клиент отправляет в службу с ресурсами предварительный (preflight) CORS-запрос с определенными параметрами в заголовках HTTP (CORS-заголовках, если быть точнее). Служба отвечает, используя те же заголовки с другими или такими же значениями. На основе ответа на предварительный CORS-запрос клиент решает, может ли он отправить основной запрос к службе. Браузер (клиент) выдаст ошибку, если ответ не соответствует требованиям предварительной проверки CORS.

Предварительные CORS-запросы отправляются независимо от используемых для отправки запросов из браузера библиотек или фреймворков. Поэтому вам не нужно соответствовать требованиям CORS, когда вы работе с API из вашего серверного приложения.

CORS не будет препятствовать пользователям запрашивать или загружать ресурсы. Вы прежнему можете успешно запросить ресурс с помощью таких приложений, как curl, Insomnia или Postman. CORS будет препятствовать доступу браузера к ресурсу только в том случае, если политика CORS не разрешает этого.

Что такое предварительная проверка CORS?

Когда браузер отправляет запрос на сервер, он сначала отправляет Options HTTP-запрос. Это и есть предварительным CORS-запрос. Затем сервер отвечает списком разрешенных методов и заголовков. Если браузеру разрешено сделать фактический запрос, то тогда он незамедлительно отправит его. Если нет, он покажет пользователю ошибку и не выполнит основной запрос.

CORS-заголовки

CORS-заголовки — это обычные заголовки HTTP, которые используются для контроля политики CORS. Они используются, когда браузер отправляет предварительный CORS-запрос на сервер, на который сервер отвечает следующими заголовками:

  • Access-Control-Allow-Origin указывает, какой источник может получать ресурсы. Вы можете указать один или несколько источников через запятую, например: https://foo.io,http://bar.io.

  • Access-Control-Allow-Methods указывает, какие HTTP-методы разрешены. Вы можете указать один или несколько HTTP-методов через запятую, например: GET,PUT,POST.

  • Access-Control-Allow-Headers указывает, какие заголовки запросов разрешены. Вы можете указать один или несколько заголовков через запятую, например: Authorization,X-My-Token.

  • Access-Control-Allow-Credentials указывает, разрешена ли отправка файлов cookie. По умолчанию: false.

  • Access-Control-Max-Age указывает в секундах, как долго должен кэшироваться результат запроса. По умолчанию: 0.

Если вы решите использовать Access-Control-Allow-Credentials=true, то вам нужно знать, что вы не сможете использовать символы * в заголовках Access-Control-Allow-*. Необходимо будет явно перечислить все разрешенные источники, методы и заголовки.

Полный список CORS-заголовков вы можете найти здесь.

Почему запрос может быть заблокирован политикой CORS?

Если вы веб-разработчик, вы, вероятно, уже слышали или даже сталкивались с CORS-ошибками, имея за плечами часы, потраченные на поиски их причин и решений. Наиболее распространенная проблема заключается в том, что браузер блокирует запрос из-за политики CORS. Браузер выдаст ошибку и отобразит в консоли следующее сообщение:

Access to XMLHttpRequest at 'http://localhost:8080/' from origin
'http://localhost: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.

Приведенная выше CORS-ошибка уведомляет пользователя о том, что браузер не может получить доступ к ресурсу (https://localhost:8080) из источника (https://localhost:3000), поскольку сервер его не одобрил. Это произошло из-за того, что сервер не ответил заголовком Access-Control-Allow-Origin с этим источником или символом * в ответе на предварительный CORS-запрос.

Запрос может быть заблокирован политикой CORS не только из-за невалидного источника, но и из-за неразрешенных заголовка HTTP, HTTP-метода или заголовка Cookie.

Как исправить CORS-ошибку?

Фундаментальная идея “исправления CORS” заключается в том, чтобы отвечать на OPTIONS запросы, отправленные от клиента, корректными заголовками. Есть много способов начать отвечать корректными CORS. Вы можете использовать прокси-сервер или какое-нибудь middleware на своем сервере.

Помните, что заголовки Access-Control-* кэшируются в браузере в соответствии со значением, установленным в заголовке Access-Control-Max-Age. Поэтому перед тестированием изменений вам обязательно нужно чистить кэш. Вы также можете отключить кэширование в своем браузере.

1. Настройка вашего сервера

По умолчанию, если вы являетесь владельцем сервера, вам необходимо настроить на своем сервере CORS-ответы, и это единственный способ правильно решить проблему. Вы можете добиться этого несколькими способами из нескольких слоев вашего приложения. Самый распространенный способ — использовать обратный прокси-сервер (reverse-proxy), API-шлюз или любой другой сервис маршрутизации, который позволяет добавлять заголовки к ответам. Для этого можно использовать множество сервисов, и вот некоторые из них: HAProxy, Linkerd, Istio, Kong, nginx, Apache, Traefik. Если ваша инфраструктура содержит только приложение без каких-либо дополнительных слоев, то вы можете добавить поддержку CORS в код самого приложения.

Вот несколько популярных примеров активации CORS:

  • Apache: отредактируйте файл .htaccess

  • Nginx: отредактируйте файл конфигурации,

  • Traefik: используйте middleware,

  • Spring Boot: используйте аннотацию @EnableCORS,

  • ExpressJS: используйте app.use(cors()),

  • NextJS: используйте реквест-хелперы.

Здесь вы можете найти больше примеров активации CORS для разных фреймворков и языков: enable-cors.org.

Если вы не можете активировать CORS в службе, но все же хотите сделать возможными запросы к ней, то вам нужно использовать одно из следующих решений, описанных ниже.

2. Установка расширения для браузера

Использование расширения для браузера может быть быстрым и простым способом решения проблем с CORS в вашей среде разработки. Самым большим преимуществом использования расширения для браузера является то, что вам не нужно менять свой код или конфигурацию. С другой стороны, вам необходимо установить расширение в каждый браузер, который вы используете для тестирования своего веб-приложения.

Расширения для браузера изменяют входящий предварительный запрос, добавляя необходимые заголовки, чтобы обмануть браузер. Это очень удобное решение для локальной работы с производственным API, которое принимает запросы только из рабочего домена.

Вы можете найти расширения в Google Web Store или в библиотеке дополнений Mozilla. В некоторых случаях дефолтной конфигурации расширения может быть недостаточно; убедитесь, что установленное расширение корректно настроено. Вам также следует быть в курсе, что если держать подобное расширение включенным постоянно, то это может вызвать проблемы с некоторыми сайтами. Их рекомендуется использовать только в целях разработки.

3. Отключение CORS-проверок в браузере

Вы можете полностью отключить CORS-проверки в своем браузере. Чтобы отключить CORS-проверки в Google Chrome, нужно закрыть браузер и запустить его с флагами --disable-web-security и --user-data-dir. После запуска Google Chrome не будет отправлять предварительные CORS-запросы и не будет проверять CORS-заголовки.

# Windows
chrome.exe --user-data-dir="C://chrome-dev-disabled-security" --disable-web-security --disable-site-isolation-trials

# macOS
open /Applications/Google Chrome.app --args --user-data-dir="/var/tmp/chrome-dev-disabled-security" --disable-web-security --disable-site-isolation-trials

# Linux
google-chrome --user-data-dir="~/chrome-dev-disabled-security" --disable-web-security --disable-site-isolation-trials

Все команды, приведенные выше, запускают Google Chrome в изолированной безопасной среде. Они не затронут ваш основной профиль Chrome.

Список всех доступных флагов для Google Chrome можно найти здесь.

4. Настройка прокси-сервера

Если вы ищете решение, которое не требует от вас изменения настроек браузера, вам следует обратить внимание на прокси-сервера. Эта опция поможет вам избавиться от CORS-ошибок, ничего не меняя в самом браузере. Идея подхода заключается в том, чтобы отправлять все запросы на ваш сервер, который затем перенаправит запрос реальной службе, которую вы хотите использовать. Вы можете создать прокси-сервер самостоятельно с помощью языка и платформы по вашему предпочтению. Вам потребуется настроить CORS и реализовать функционал передачи полученных запросов в другую службу.

Прокси-сервер — хорошее решение, если у вас нет доступа к службе, которую вы собираетесь использовать. Существует множество готовых к использованию решений с открытым исходным кодом для создания прокси-серверов, но вам обязательно нужно следить за тем, чтобы они не пытались перехватить ваши запросы с заголовками авторизации и передать их какой-либо сторонней службе. Такие нарушения безопасности могут привести к катастрофическим последствиям как для вас, так и для потенциальных пользователей службы.

Ниже приведен список CORS сервисов с открытым исходным кодом, которые вы можете найти на просторах интернета:

  • https://github.com/Freeboard/thingproxy

  • https://github.com/bulletmark/corsproxy

  • https://github.com/Rob—W/cors-anywhere

Перед использованием любого из этих сервисов обязательно проверьте код самой последний версии версии.

Как протестировать CORS?

Использование браузера для проверки конфигурации CORS может оказаться на удивление утомительной задачей. В качестве альтернативы вы можете использовать такие инструменты, как CORS Tester, test-cors.org или, если вас не страшит командная строка, вы можете использовать curl для проверки конфигурации CORS.

curl -v -X OPTIONS https://simplelocalize.io/api/v1/translations

Остерегайтесь ложных CORS-ошибок

В некоторых случаях, когда сервис находится за дополнительным слоем защиты ограничителя частоты запросов, балансировщика нагрузки или сервера авторизации, вы можете получить ложную CORS-ошибку. Заблокированные или отклоненные сервером запросы должны отвечать статус кодами ошибки. Например:

  • 401 unauthorized,

  • 403 forbidden,

  • 429 too many requests,

  • 500 internal server error,

  • любые, кроме 2XX или 3XX.

Вы можете видеть, что запрос заблокирован из-за неудачного предварительного запроса, но на самом деле служба просто отклоняет его. Вы всегда должны проверять статус код и текст ответа, чтобы избежать излишней отладки. Браузер должным образом уведомляет вас о сбое в предварительном CORS-запросе, но причина сбоя может быть не связана с конфигурацией CORS.

Заключение

В этой статье я постарался объяснить, что такое CORS и каковы наиболее распространенные проблемы с ним. Я предложил четыре способа избавиться от проблемы с CORS и объяснил преимущества и недостатки каждого из них. Я также объяснил, как правильно настроить CORS-ответы и как их протестировать. Более того, я показал самые распространенные проблемы, с которыми вы можете столкнуться при распознавании ложных CORS-ошибок. Я постарался изложить все максимально простым языком и избежать мудреных технических подробностей. Cпасибо за внимание!

Полезные ссылки

  • https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors

  • https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy

  • https://enable-cors.org/

  • https://stackoverflow.com/a/42024918/1133169


Материал подготовлен в преддверии старта онлайн-курса «JavaScript Developer. Professional». Недавно прошел открытый урок на тему «CSS-in-JS. Удобный способ управлять стилями», на котором рассмотрели Styled components, Linaria, Astroturf и другие инструменты упрощения работы со стилями. Посмотреть запись можно по ссылке.

Andy Potts

Andy Potts

Posted on Jul 23, 2020

• Updated on Jul 31, 2020

• Originally published at Medium



 



 



 



 



 

When developing a website/web app on localhost which makes requests to another server, you might run into Cross Origin Resource Sharing (CORS) issues. I won’t go into too much detail about what CORS is in this post. All I will say is that CORS exists for security reasons, but when you’re developing locally it can be a pain! You can read more about CORS on the MDN docs.

I have written this simple guide to explain the main solutions for disabling cross origin restrictions on localhost (and therefore fixing any CORS errors whilst developing your app locally), which I will explain in more detail below.


1. Use the proxy setting in Create React App

Create React App comes with a config setting which allows you to simply proxy API requests in development. This is available in react-scripts@0.2.3. To do this add the proxy setting to your package.json like this

"proxy": "https://cat-fact.herokuapp.com/",

Now when you make an API request to https://localhost:3000/api/facts Create React App will proxy the API request to https://cat-fact.herokuapp.com/facts and the CORS error will be resolved. 

This is a really simple solution which might not work with more complicated situations where multiple API’s are involved, or certain types of API authentication is needed.

2. Disable CORS in the browser

You can directly disable CORS in the browser. If you do this, please be aware that you are disabling security restrictions which are there for a reason. I wouldn’t recommend browsing the web with CORS disabled; Just disable it whilst developing your website/app.

Chrome:

The most reliable way to disable CORS in the latest version of Chrome on Mac (tested on v84) is to run it with web security disabled.

  1. Force quit Chrome by going to the mac menu and pressing “force quit” (or pressing command Q).
  2. Then run this command to open Chrome with web security disabled
open -n -a /Applications/Google Chrome.app/Contents/MacOS/Google Chrome — args — user-data-dir=”/tmp/chrome_dev_test” — disable-web-security

Once you’re done developing, restart Chrome and it will go back to normal.

Firefox:

The easiest and most reliable way to disable CORS in Firefox is to install the CORS Everywhere plugin.

Safari:

The easiest and most reliable way to CORS in Safari is to disable CORS in the develop menu.

  1. Enable the develop menu by going to Preferences > Advanced.
  2. Then select “Disable Cross-Origin Restrictions” from the develop menu.

Once you’re done developing, restart Safari and it will go back to normal.


3. Use a proxy to avoid CORS errors

Alternatively you could use a proxy like cors-anywhere.
If you want to easily demo cors-anywhere, Rob — W has setup a public demo which is great for consuming public API’s as it requires no registration or config https://cors-anywhere.herokuapp.com. As it’s just a demo, requests are limited.

To use the public demo of cors-anywhere, just add the url you want to make the request to after the domain e.g. https://cors-anywhere.herokuapp.com/https://cat-fact.herokuapp.com/facts (*if you view this in the browser you might get an error about a missing request header. When you make an API request using in your app using something like Axios or Fetch this won’t be an issue).


If you found this useful, have any questions, or want more content like this, feel free to follow me on twitter!

Many websites have JavaScript functions that make network requests to a server, such as a REST API. The web pages and APIs are often in different domains. This introduces security issues in that any website can request data from an API. Cross-Origin Resource Sharing (CORS) provides a solution to these issues. It became a W3C recommendation in 2014. It makes it the responsibility of the web browser to prevent unauthorized access to APIs. All modern web browsers enforce CORS. They prevent JavaScript from obtaining data from a server in a domain different than the domain the website was loaded from, unless the REST API server gives permission.

From a developer’s perspective, CORS is often a cause of much grief when it blocks network requests. CORS provides a number of different mechanisms for limiting JavaScript access to APIs. It is often not obvious which mechanism is blocking the request. We are going to build a simple web application that makes REST calls to a server in a different domain. We will deliberately make requests that the browser will block because of CORS policies and then show how to fix the issues. Let’s get started!

NOTE: The code for this project can be found on GitHub.

Table of Contents

  • Prerequisites to Building a Go Application
  • How to Build a Simple Web Front End
  • How to Build a Simple REST API in Go
  • How to Solve a Simple CORS Issue
  • Allowing Access from Any Origin Domain
  • CORS in Flight
  • What Else Does CORS Block?
  • Restrictions on Response Headers
  • Credentials Are a Special Case
  • Control CORS Cache Configuration
  • How to Prevent CORS Issues with Okta
  • How CORS Prevents Security Issues

Prerequisites to Building a Go Application

First things first, if you don’t already have Go installed on your computer you will need to download and install the Go Programming Language.

Now, create a directory where all of our future code will live.

Finally, we will make our directory a Go module and install the Gin package (a Go web framework) to implement a web server.

go mod init cors
go get github.com/gin-gonic/gin
go get github.com/gin-contrib/static

A file called go.mod will get created containing the dependencies.

How to Build a Simple Web Front End

We are going to build a simple HTML and JavaScript front end and serve it from a web server written using Gin.

First of all, create a directory called frontend and create a file called frontend/index.html with the following content:

<html>
    <head>
        <meta charset="UTF-8" />
        <title>Fixing Common Issues with CORS</title>
    </head>
    <body>
        <h1>Fixing Common Issues with CORS</h1>
        <div>
            <textarea id="messages" name="messages" rows="10" cols="50">Messages</textarea><br/>
            <form id="form1">
                <input type="button" value="Get v1" onclick="onGet('v1')"/>
                <input type="button" value="Get v2" onclick="onGet('v2')"/>
            </form>
        </div>
    </body>
</html>

The web page has a text area to display messages and a simple form with two buttons. When a button is clicked it calls the JavaScript function onGet() passing it a version number. The idea being that v1 requests will always fail due to CORS issues, and v2 will fix the issue.

Next, create a file called frontend/control.js containing the following JavaScript:

function onGet(version) {
    const url = "http://localhost:8000/api/" + version + "/messages";
    var headers = {}
    
    fetch(url, {
        method : "GET",
        mode: 'cors',
        headers: headers
    })
    .then((response) => {
        if (!response.ok) {
            throw new Error(response.error)
        }
        return response.json();
    })
    .then(data => {
        document.getElementById('messages').value = data.messages;
    })
    .catch(function(error) {
        document.getElementById('messages').value = error;
    });
}

The onGet() function inserts the version number into the URL and then makes a fetch request to the API server. A successful request will return a list of messages. The messages are displayed in the text area.

Finally, create a file called frontend/.go containing the following Go code:

package main

import (
	"github.com/gin-contrib/static"
	"github.com/gin-gonic/gin"
)

func main() {
	r := gin.Default()
	r.Use(static.Serve("/", static.LocalFile("./frontend", false)))
	r.Run(":8080")
}

This code simply serves the contents of the frontend directory on requests on port 8080. Note that JavaScript makes a call to port http://localhost:8000 which is a separate service.

Start the server and point a web browser at http://localhost:8080 to see the static content.

How to Build a Simple REST API in Go

Create a directory called rest to contain the code for a basic REST API.

NOTE: A separate directory is required as Go doesn’t allow two program entry points in the same directory.

Create a file called rest/server.go containing the following Go code:

package main

import (
	"fmt"
	"strconv"
	"net/http"

	"github.com/gin-gonic/gin"
)

var messages []string

func GetMessages(c *gin.Context) {
	version := c.Param("version")
	fmt.Println("Version", version)
	c.JSON(http.StatusOK, gin.H{"messages": messages})
}

func main() {
	messages = append(messages, "Hello CORS!")
	r := gin.Default()
	r.GET("/api/:version/messages", GetMessages)
	r.Run(":8000")
}

A list called messages is created to hold message objects.

The function GetMessages() is called whenever a GET request is made to the specified URL. It returns a JSON string containing the messages. The URL contains a path parameter which will be v1 or v2. The server listens on port 8000.

The server can be run using:

How to Solve a Simple CORS Issue

We now have two servers—the front-end one on http://localhost:8080, and the REST API server on http://localhost:8000. Even though the two servers have the same hostname, the fact that they are listening on different port numbers puts them in different domains from the CORS perspective. The domain of the web content is referred to as the origin. If the JavaScript fetch request specifies cors a request header will be added identifying the origin.

Origin: http://localhost:8080

Make sure both the frontend and REST servers are running.

Next, point a web browser at http://localhost:8080 to display the web page. We are going to get JavaScript errors, so open your browser’s developer console so that we can see what is going on. In Chrome it is *View** > Developer > Developer Tools.

Next, click on the Send v1 button. You will get a JavaScript error displayed in the console:

Access to fetch at ‘http://localhost:8000/api/v1/messages’ from origin ‘http://localhost:8080’ has been blocked by CORS policy: 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.

The message says that the browser has blocked the request because of a CORS policy. It suggests two solutions. The second suggestion is to change the mode from cors to no-cors in the JavaScript fetch request. This is not an option as the browser always deletes the response data when in no-cors mode to prevent data from being read by an unauthorized client.

The solution to the issue is for the server to set a response header that allows the browser to make cross-domain requests to it.

Access-Control-Allow-Origin: http://localhost:8080

This tells the web browser that the cross-origin requests are to be allowed for the specified domain. If the domain specified in the response header matches the domain of the web page, specified in the Origin request header, then the browser will not block the response being received by JavaScript.

We are going to set the header when the URL contains v2. Change the GetMessages() function in cors/server.go to the following:

func GetMessages(c *gin.Context) {
	version := c.Param("version")
	fmt.Println("Version", version)
	if version == "v2" {
		c.Header("Access-Control-Allow-Origin", "http://localhost:8080")
	}
	c.JSON(http.StatusOK, gin.H{"messages": messages})
}

This sets a header to allow cross-origin requests for the v2 URI.

Restart the server and go to the web page. If you click on Get v1 you will get blocked by CORS. If you click on Get v2, the request will be allowed.

A response can only have at most one Access-Control-Allow-Origin header. The header can only specify only one domain. If the server needs to allow requests from multiple origin domains, it needs to generate an Access-Control-Allow-Origin response header with the same value as the Origin request header.

Allowing Access from Any Origin Domain

There is an option to prevent CORS from blocking any domain. This is very popular with developers!

Access-Control-Allow-Origin: *

Be careful when using this option. It will get flagged in a security audit. It may also be in violation of an information security policy, which could have serious consequences!

CORS in Flight

Although we have fixed the main CORS issue, there are some limitations. One of the limitations is that only the HTTP GET, and OPTIONS methods are allowed. The GET and OPTIONS methods are read-only and are considered safe as they don’t modify existing content. The POST, PUT, and DELETE methods can add or change existing content. These are considered unsafe. Let’s see what happens when we make a PUT request.

First of all, add a new form to client/index.html:

<form id="form2">
    <input type="text" id="puttext" name="puttext"/>
    <input type="button" value="Put v1" onclick="onPut('v1')"/>
    <input type="button" value="Put v2" onclick="onPut('v2')"/>
</form>

This form has a text input and the two send buttons as before that call a new JavaScript function.

Next, add the JavaScript funtion to client/control.js:

function onPut(version) {
    const url = "http://localhost:8000/api/" + version + "/messages/0";
    var headers = {}

    fetch(url, {
        method : "PUT",
        mode: 'cors',
        headers: headers,
        body: new URLSearchParams(new FormData(document.getElementById("form2"))),
    })
    .then((response) => {
        if (!response.ok) {
            throw new Error(response.error)
        }
        return response.json();
    })
    .then(data => {
        document.getElementById('messages').value = data.messages;
    })
    .catch(function(error) {
        document.getElementById('messages').value = error;
    });
}

This makes a PUT request sending the form parameters in the request body. Note that the URI ends in /0. This means that the request is to create or change the message with the identifier 0.

Next, define a PUT handler in the main() function of rest/server.go:

r.PUT("/api/:version/messages/:id", PutMessage)

The message identifier is extracted as a path parameter.

Finally, add the request handler function to rest/server.go:

func PutMessage(c *gin.Context) {
	version := c.Param("version")
	id, _ := strconv.Atoi(c.Param("id"))
	text := c.PostForm("puttext")
	messages[id] = text
	if version == "v2" {
	    c.Header("Access-Control-Allow-Origin", "http://localhost:8080")
	}
	c.JSON(http.StatusOK, gin.H{"messages": messages})
}

This updates the message from the form data and sends the new list of messages. The function also always sets the allow origin header, as we know that it is required.

Now, restart the servers and load the web page. Make sure that the developer console is open. Add some text to the text input and hit the Send v1 button.

You will see a slightly different CORS error in the console:

Access to fetch at ‘http://localhost:8000/api/v1/messages/0’ 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. If an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.

This is saying that a preflight check was made, and that it didn’t set the Access-Control-Allow-Origin header.

Now, look at the console output from the API server:

[GIN] 2020/12/01 - 11:10:09 | 404 |  447ns |  ::1 | OPTIONS  "/api/v1/messages/0"

So, what is happening here? JavaScript is trying to make a PUT request. This is not allowed by CORS policy. In the GET example, the browser made the request and blocked the response. In this case, the browser refuses to make the PUT request. Instead, it sent an OPTIONS request to the same URI. It will only send the PUT if the OPTIONS request returns the correct CORS header. This is called a preflight request. As the server doesn’t know what method the OPTIONS preflight request is for, it specifies the method in a request header:

Access-Control-Request-Method: PUT

Let’s fix this by adding a handler for the OPTIONS request that sets the allow origin header in cors/server.go:

func OptionMessage(c *gin.Context) {
	c.Header("Access-Control-Allow-Origin", "http://localhost:8080")
}

func main() {
	messages = append(messages, "Hello CORS!")
	r := gin.Default()
	r.GET("/api/:version/messages", GetMessages)
	r.PUT("/api/:version/messages/:id", PutMessage)
	r.OPTIONS("/api/v2/messages/:id", OptionMessage)
	r.Run(":8000")
}

Notice that the OPTIONS handler is only set for the v2 URI as we don’t want to fix v1.

Now, restart the server and send a message using the Put v2 button. We get yet another CORS error!

Access to fetch at ‘http://localhost:8000/api/v2/messages/0’ from origin ‘http://localhost:8080’ has been blocked by CORS policy: Method PUT is not allowed by Access-Control-Allow-Methods in preflight response.

This is saying that the preflight check needs another header to stop the PUT request from being blocked.

Add the response header to cors/server.go:

func OptionMessage(c *gin.Context) {
	c.Header("Access-Control-Allow-Origin", "http://localhost:8080")
	c.Header("Access-Control-Allow-Methods", "GET, OPTIONS, POST, PUT")
}

Restart the server and resend the message. The CORS issues are resolved.

What Else Does CORS Block?

CORS has a very restrictive policy regarding which HTTP request headers are allowed. It only allows safe listed request headers. These are Accept, Accept-Language, Content-Language, and Content-Type. They can only contain printable characters and some punctuation characters are not allowed. Header values can’t have more than 128 characters.

There are further restrictions on the Content-Type header. It can only be one of application/x-www-form-urlencoded, multipart/form-data, and text/plain. It is interesting to note that application/json is not allowed.

Let’s see what happens if we send a custom request header. Modify the onPut() function in frontend/control.jsto set a header:

var headers = { "X-Token": "abcd1234" }

Now, make sure that the servers are running and load or reload the web page. Type in a message and click the Put v1 button. You will see a CORS error in the developer console.

Access to fetch at ‘http://localhost:8000/api/v2/messages/0’ from origin ‘http://localhost:8080’ has been blocked by CORS policy: Request header field x-token is not allowed by Access-Control-Allow-Headers in preflight response.

Any header which is not CORS safe-listed causes a preflight request. This also contains a request header that specifies the header that needs to be allowed:

Access-Control-Request-Headers: x-token

Note that the header name x-token is specified in lowercase.

The preflight response can allow non-safe-listed headers and can remove restrictions on safe listed headers:

Access-Control-Allow-Headers: X_Token, Content-Type

Next, change the function in cors/server.go to allow the custom header:

func OptionMessage(c *gin.Context) {
	c.Header("Access-Control-Allow-Origin", "http://localhost:8080")
	c.Header("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT")
	c.Header("Access-Control-Allow-Headers", "X-Token")
}

Restart the server and resend the message by clicking the Put v2 button. The request should now be successful.

CORS also places restrictions on response headers. There are seven whitelisted response headers: Cache-Control, Content-Language, Content-Length, Content-Type, Expires, Last-Modified, and Pragma. These are the only response headers that can be accessed from JavaScript. Let’s see this in action.

First of all, add a text area to frontend/index.html to display the headers:

<textarea id="headers" name="headers" rows="10" cols="50">Headers</textarea><br/>

Next, replace the first then block in the onPut function in frontend/control.js to display the response headers:

.then((response) => {
    if (!response.ok) {
        throw new Error(response.error)
    }
    response.headers.forEach(function(val, key) {
        document.getElementById('headers').value += 'n' + key + ': ' + val; 
    });
    return response.json();
})

Finally, set a custom header in rest/server.go:

func PutMessage(c *gin.Context) {
	version := c.Param("version")
	id, _ := strconv.Atoi(c.Param("id"))
	text := c.PostForm("puttext")
	messages[id] = text
	if version == "v2" {
	    c.Header("Access-Control-Allow-Origin", "http://localhost:8080")
	}
	c.Header("X-Custom", "123456789")
	c.JSON(http.StatusOK, gin.H{"messages": messages})
}

Now, restart the server and reload the web page. Type in a message and hit Put v2. You should see some headers displayed, but not the custom header. CORS has blocked it.

This can be fixed by setting another response header to expose the custom header in server/server.go:

func PutMessage(c *gin.Context) {
	version := c.Param("version")
	id, _ := strconv.Atoi(c.Param("id"))
	text := c.PostForm("puttext")
	messages[id] = text
	if version == "v2" {
        c.Header("Access-Control-Expose-Headers", "X-Custom")
	    c.Header("Access-Control-Allow-Origin", "http://localhost:8080")
	}
	c.Header("X-Custom", "123456789")
	c.JSON(http.StatusOK, gin.H{"messages": messages})
}

Restart the server and reload the web page. Type in a message and hit Put v2. You should see some headers displayed, including the custom header. CORS has now allowed it.

Credentials Are a Special Case

There is yet another CORS blocking scenario. JavaScript has a credentials request mode. This determines how user credentials, such as cookies are handled. The options are:

  • omit: Never send or receive cookies.
  • same-origin: This is the default, that allows user credentials to be sent to the same origin.
  • include: Send user credentials even if cross-origin.

Let’s see what happens.

Modify the fetch call in the onPut() function in frontend/Control.js:

fetch(url, {
    method : "PUT",
    mode: 'cors',
    credentials: 'include',
    headers: headers,
    body: new URLSearchParams(new FormData(document.getElementById("form2"))),
})

Now, make sure that the client and server are running and reload the web page. Send a message as before. You will get another CORS error in the developer console:

Access to fetch at ‘http://localhost:8000/api/v2/messages/0’ from origin ‘http://localhost:8080’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: The value of the ‘Access-Control-Allow-Credentials’ header in the response is ‘’ which must be ‘true’ when the request’s credentials mode is ‘include’.

The fix for this is to add another header to both the OptionMessage(), and PutMessage() functions in cors/server.go as the header needs to be present in both the preflight request and the actual request:

c.Header("Access-Control-Allow-Credentials", "true")

The request should now work correctly.

The credentials issue can also be resolved on the client by setting the credentials mode to omit and sending credentials as request parameters, instead of using cookies.

Control CORS Cache Configuration

The is one more CORS header that hasn’t yet been discussed. The browser can cache the preflight request results. The Access-Control-Max-Age header specifies the maximum time, in seconds, the results can be cached. It should be added to the preflight response headers as it controls how long the Access-Control-Allow-Methods and Access-Control-Allow-Headers results can be cached.

Access-Control-Max-Age: 600

Browsers typically have a cap on the maximum time. Setting the time to -1 prevents caching and forces a preflight check on all calls that require it.

How to Prevent CORS Issues with Okta

Authentication providers, such as Okta, need to handle cross-domain requests to their authentication servers and API servers. This is done by providing a list of trusted origins. See Okta Enable CORS for more information.

How CORS Prevents Security Issues

CORS is an important security feature that is designed to prevent JavaScript clients from accessing data from other domains without authorization.

Modern web browsers implement CORS to block cross-domain JavaScript requests by default. The server needs to authorize cross-domain requests by setting the correct response headers.

CORS has several layers. Simply allowing an origin domain only works for a subset of request methods and request headers. Some request methods and headers force a preflight request as a further means of protecting data. The actual request is only allowed if the preflight response headers permit it.

CORS is a major pain point for developers. If a request is blocked, it is not easy to understand why, and how to fix it. An understanding of the nature of the blocked request, and of the CORS mechanisms, can easily overcome such issues.

If you enjoyed this post, you might like related ones on this blog:

  • What is the OAuth 2.0 Implicit Grant Type?
  • Combat Side-Channel Attacks with Cross-Origin Read Blocking

Follow us for more great content and updates from our team! You can find us on Twitter, Facebook, subscribe to our YouTube Channel or start the conversation below.

Published 2022-07-08

When you send an HTTP request with a different domain than your page’s domain (or IP address + port number), a CORS error will occur. A CORS error means that the API server rejected your request. To access other domain API from your web page, the backend server you requested must set some CORS headers in the HTTP response to allow CORS requests. Below are some errors caused by incorrectly set HTTP response headers for CORS requests.

Error information in web browser console

1
2
Access to XMLHttpRequest at 'http://localhost:8081/api' from origin 'http://localhost' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
GET http://localhost:8081/api net::ERR_FAILED 302

Solutions

First, check that the URL, Method, and Content-Type you requested are correct.

Make sure the server API is up and running.

Enable CORS requests for your server API. Add Access-Control-Allow-Origin in HTTP response header.

1
2
3
Access-Control-Allow-Origin: *
or
Access-Control-Allow-Origin: http://your_page_domain

For example, in Java web projects.

1
2
3
response.setHeader("Access-Control-Allow-Origin", "*");

response.setHeader("Access-Control-Allow-Origin", "http://localhost");

Reasons

The API is not shared with other origins. You need to update the API CORS policy by set Access-Control-Allow-Origin in response headers.

Error: Method xxx is not allowed

Error information in web browser console

1
Access to XMLHttpRequest at 'http://localhost:8081/api/delete' from origin 'http://localhost' has been blocked by CORS policy: Method DELETE is not allowed by Access-Control-Allow-Methods in preflight response.

Solutions

Add Access-Control-Allow-Methods: {method_name_in_error_message} in HTTP response header. Note that method names must be capitalized.

For example, in Java web projects.

1
response.setHeader("Access-Control-Allow-Methods", "DELETE");

Reasons

The default allowed HTTP methods for CORS are GET, POST, and HEAD. For other HTTP methods like DELETE or PUT, you need to add it to HTTP response header Access-Control-Allow-Methods.

Error information in web browser console

1
Access to XMLHttpRequest at 'http://localhost:8081/api/delete' from origin 'http://localhost' has been blocked by CORS policy: Request header field my-header1 is not allowed by Access-Control-Allow-Headers in preflight response.
1
Access to XMLHttpRequest at 'http://localhost:8081/api/get?name=Jack' from origin 'http://localhost' has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.

Solutions

Add Access-Control-Allow-Headers: {header_field_name_in_error_message} in HTTP response header.

For example, in Java web projects.

1
response.setHeader("Access-Control-Allow-Headers", "my-header1");

Reasons

The default allowed HTTP headers for CORS requests are:

  • Accept
  • Accept-Language
  • Content-Language
  • Content-Type (value only be application/x-www-form-urlencoded, multipart/form-data, or text/plain)
  • Range

For other HTTP headers, you need to add them to HTTP response header Access-Control-Allow-Headers.

Error information in web browser console

1
Access to XMLHttpRequest at 'http://localhost:8081/api/get' from origin 'http://localhost' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

Solutions

Set the value of Access-Control-Allow-Origin to your page domain instead of * in HTTP response header. And set the value of Access-Control-Allow-Credentials to true.

For example, in Java web projects.

1
2
response.setHeader("Access-Control-Allow-Origin", "http://localhost");
response.setHeader("Access-Control-Allow-Credentials", "true");

Reasons

When you send a CORS request with credentials, you must set a specific domain in Access-Control-Allow-Origin.

CORS request with credentials: withCredentials: true

1
2
3
4
5
6
7
8
9
10
11
12
const xhr = new XMLHttpRequest();
const url = 'http://localhost:8081/api/get';
xhr.open('GET', url, true);
xhr.withCredentials = true;
xhr.onload = function () {
if (xhr.readyState === xhr.DONE) {
if (xhr.status === 200) {
console.log(xhr.response);
}
}
};
xhr.send();
1
2
3
4
5
6
7
8
9
$.ajax({
url: "http://localhost:8081/api/get",
method: "GET",
xhrFields: {
withCredentials: true
},
}).done(function(res) {
console.log(res);
});

Error information in web browser console

1
Access to XMLHttpRequest at 'http://localhost:8081/api/get' from origin 'http://localhost' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

Solutions

Add Access-Control-Allow-Credentials: true in HTTP response header.

For example, in Java web projects.

1
response.setHeader("Access-Control-Allow-Credentials", "true");

Reasons

When the request’s credentials flag is true, the HTTP response header Access-Control-Allow-Credentials should be true.

Like this post? Please share to your friends:
  • Ошибка cors javascript
  • Ошибка connectionfailure что это значит как исправить
  • Ошибка cors django
  • Ошибка cors ajax
  • Ошибка corrupt data found please verify your installation