Provisional headers are shown ошибка

If you’re familiar with Chrome DevTools, you certainly have seen the “Provisional headers are shown” warning message popped up in certain network requests.

In this article, we will explain what exactly “Provisional headers” are, and what does “Provisional headers are shown” means in Google Chrome/Chromium-based browsers.

HTTP headers are the name or value pairs that are displayed in the request and response messages of message headers for Hypertext Transfer Protocol (HTTP). Request headers contain more information about the resource to be fetched, or about the client requesting the resource. Response headers hold additional information about the response, like its location or about the server providing it. These headers are usually invisible to the end-user and are only processed or logged by the server and client applications.

HTTP Headers displayed for pending requests are provisional. They represent what request was sent from Blink to Chromium/Chrome. To those of you who didn’t know, Blink is the open-source browser layout engine that powers Chromium (and therefore Chrome as well).

Chromium/Chrome do not update headers until server responds to avoid additional notification used only by DevTools. In short, provisional headers mean the requests they are not yet responded to. Please do note that this is just a notification, not an actual error message.

If the request is meant to be responded properly, but in reality, “Provisional headers are shown” are displayed, it’s usually because one of these reasons:

  • An extension has blocked your request
  • Chrome use its own cache to fetch your resource. The request was not sent over the network and instead was served from a local cache, which doesn’t store the original request headers.
  • Internal error which made Chrome cannot get your request headers from a request that haven’t made.

Check your adblockers

One of the most common reasons that causes “Provisional headers are shown” are Chrome extensions. The resource you’re trying to load could be being blocked by an extension, usually ad-blockers such as AdBlock, uBlock Origin or Adguard.

Most adblockers work the same way, which is blocking the requests based on pattern matching. If an URL contains the word “advert”, “ads” or something similar, it would be blocked from loading.

In order to make “Provisional headers are shown” disappear, you’ll have to whitelist the URL out of adblockers block list. Below are instructions on how to do that with popular extensions like Adblock Plus and uBlock Origin.

Whitelist your site from Adblock Plus

  1. Navigate to the URL which have been blocked and shown “Provisional headers are shown”.
  2. Click on the AdBlock Plus icon in the Chrome toolbar. If you don’t see the icon, it may be hidden by Chrome/Chromium itself. Clicking the “jigsaw” icon will bring you the full list of all installed extensions.
  3. Click the toggle in Block ads on this website section to whitelist the whole domain out of Adblock Plus blocklist. Alternatively, you can whitelist only the URL you’re visiting by clicking the smaller toggle on This page section.

Whitelist your site from uBlock Origin

  1. Navigate to the URL which have been blocked and shown “Provisional headers are shown”.
  2. uBlock circumvents immediately and show you a message which notify you that the URL has been blocked. You can either click Temporarily to unblock the URL until you close the browser, or click Permanently to unblock the URL forever.

Find the troublesome extension (Advanced)

In case your adblocker isn’t the cause of the error, there might be another extension interfering with the request-response cycle.

In order to pinpoint the exact troublesome extension, you have to use Chrome net-internals tools. How to access the tool depends on which version of Chromium/Chrome you’re using.

Latest Versions of Chrome

  • Navigate to chrome://net-export/.
  • Click Start Logging to Disk to save the logs to the hard drive. The button should change to Stop Logging
  • Open the page that is was thrown “Provisional Headers are shown”.
  • Go back to net-export page and click Stop Logging.
  • Go to https://netlog-viewer.appspot.com/#import and drag-drop the log file you’ve just saved into the webpage.
  • Click on Events (###) section in the sidebar and use the input box to find the event related to your resource (tips: use parts of the URL as search query).
  • Finally, click on the event and see if the info shown tells you something interesting.

For Older Versions of chrome

  • Type chrome://net-internals in the address bar and hit enter.
  • Open the page that is showing problems.
  • Go back to net-internals, click on Events (###) and search using input box to find the event related to your resource.
  • Finally, click on the event and see if the info shown tells you something. From these information, you can pinpoint exactly what happened and if there’s any extension breaks the request-response cycle.

Disable site isolation/network service

“Provisional Headers are shown” can also happen (for cross-origin requests only) because of a Chrome feature called site isolation. If none of the above methods work for you, you may have to try messing with site isolation/network service.

First, open up the Disable site isolation setting by navigating to chrome://flags/#chrome://flags#Disable%20site%20isolation and disable it.

Then, open up Enable Network Service setting by navigating to chrome://flags/#chrome://flags#Enable%20network%20service, and disable that:

Once you’re done, relaunch the browser and check if the issue still persists. In a few cases, users have reported that disabling cache in Chrome DevTools also help.

Alternatively, you can start Chrome with the aforementioned settings disabled by running the following command (either in Command Prompt or Linux terminal):

chrome --disable-site-isolation-trials --disable-features=NetworkService,NetworkServiceInProcess

We hope that the article offer useful information about “Provisional headers are shown” notification in Chromium/Chrome.

We’ve also written a few other guides for fixing common Chrome errors, such as Fix ERR_RESPONSE_HEADERS_MULTIPLE_CONTENT_DISPOSITION error in Google Chrome/Microsoft Edge, Fix “Requests to the server have been blocked by an extension” in Chrome/Microsoft Edge or Fix “Access to XMLHttpRequest has been blocked by CORS policy” in Chrome . If you have any suggestion, please feel free to leave a comment below.

4b9b3361

Ответ 1

Ресурс может быть заблокирован расширением (в моем случае AdBlock).

Сообщение пришло, потому что запрос на получение этого ресурса никогда не был сделан, поэтому отображаемые заголовки не являются реальными. Как объяснялось в проблеме, на которую вы ссылались, реальные заголовки обновляются, когда сервер отвечает, но нет ответа, если запрос был заблокирован.


Я узнал о расширении, которое блокировало мой ресурс, с помощью инструмента net-internals в Chrome:

Для последних версий Chrome

  • Введите chrome://net-export/ в адресной строке и нажмите ввод.
  • Начать запись. И сохраните файл записи на локальном компьютере.
  • Откройте страницу с проблемами.
  • Вернуться к net-internals
  • Вы можете просмотреть Записанный файл журнала здесь https://netlog-viewer.appspot.com/#import
  • нажмите events (###) и используйте текстовое поле, чтобы найти событие, связанное с вашим ресурсом (используйте части URL).
  • Наконец, нажмите на событие и посмотрите, говорит ли вам что-то показанная информация.

Для старых версий хрома

  • Введите chrome://net-internals в адресной строке и нажмите ввод.
  • Откройте страницу с проблемами.
  • Вернитесь к net-internals, нажмите events (###) и используйте текстовое поле, чтобы найти событие, связанное с вашим ресурсом (используйте части URL).
  • Наконец, нажмите на событие и посмотрите, говорит ли вам что-то показанная информация.

Ответ 2

Я считаю, что это происходит, когда фактический запрос не отправляется. Обычно происходит при загрузке кэшированного ресурса.

Ответ 3

Для хрома v72+ это решило только для меня следующее:

перейдите в chrome://flags/ и отключите эти 3 флага

  • Отключить изоляцию сайта
  • Включить сетевой сервис
  • Запускает сетевой сервис в процессе

enter image description here

или вы можете сделать это из командной строки:

chrome --disable-site-isolation-trials --disable-features=NetworkService,NetworkServiceInProcess

почему это случилось?

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

опасно ли это изменить?

Примером является сетевое взаимодействие: когда у нас есть сетевой сервис, мы можем выбрать его запуск вне процесса для лучшей стабильности/безопасности или внутрипроцессного, если мы ограничены в ресурсах. источник

Ответ 4

Я столкнулся с этой проблемой, и мне удалось определить конкретную причину, которая не упоминается выше ни в ответах, ни в вопросе.

Я запускаю полный стек js, angular front end и node back end на SSL, а API находится в другом домене, запущенном на порту 8081, поэтому я делаю запросы CORS и withCredentials, когда я отбрасываю cookie сеанса из API

Таким образом, в первую очередь мой сценарий был: POST-запрос, withCredentials на порт 8081 вызвал сообщение «ПРЕДОСТЕРЕЖЕНИЕ: предварительные заголовки показаны» в инспекторе, а также, конечно же, заблокировал запрос вместе.

Мое решение состояло в том, чтобы настроить apache на прокси-сервер, передав запрос с обычного порта SSL 443 на порт node SSL 8081 (node должен быть на более высоком порту, поскольку он не может быть запущен с правами root в прод). Поэтому я думаю, что Chrome не любит запросы SSL к нетрадиционным портам SSL, но, возможно, их сообщение об ошибке может быть более конкретным.

Ответ 5

Это также может произойти (только для запросов из разных источников) из-за новой функции, называемой изоляцией сайта

.На этой странице подробно описывается проблема и возможное решение. Для этого перейдите к chrome://flags/#site-isolation-trial-opt-out в Chrome, измените этот параметр на «Отказ» и перезагрузите Chrome.

Это известная проблема. Однако на этой странице написано, что она исправлена в Chrome 68, но я использую Chrome 68 и у меня все еще есть проблема.

Ответ 6

HTTP/2 Pushed resources создаст Provisional headers are shown в инспекторе для той же теории, что и @wvega, опубликованный в его ответе выше.

, например:. Так как сервер подтолкнул ресурс к клиенту (до того, как клиент запросил их), браузер имеет ресурсы, кэшированные и, следовательно, клиент никогда не делает/не требует запросов; Так что…

… реальные заголовки обновляются, когда сервер отвечает, но нет ответа, если запрос был заблокирован.

Ответ 7

Моя ситуация связана с кросс-происхождением.
Ситуация: браузер отправляет запрос OPTIONS перед отправкой реального запроса, например GET или POST. Разработчик backend забывает обрабатывать запрос OPTIONS, позволяя ему пройти через служебный код, делая слишком длительным время обработки. Дольше, чем тайм-аут, который я написал в инициализации axios, что составляет 5000 миллисекунд. Поэтому реальный запрос не может быть отправлен, а затем я столкнулся с provisional headers are shown проблему.
Решение. Когда дело доходит до запроса OPTIONS, backend api просто возвращает результат, он ускоряет запрос и реальный запрос может быть отправлен до истечения таймаута.

Ответ 8

Я сомневаюсь, что мой ответ вовремя поможет вам, но другие могут оказаться полезными. Я столкнулся с аналогичной проблемой с созданным мной jQuery Ajax Post script.

Оказалось, что у меня была опечатка в атрибуте href тега A, который я использовал для запуска сообщения. Я набрал href= « javacsript:;» (изменение «s» и «c» ). Это привело к тому, что script попытался обновить страницу во время попытки записи. скорректировал опечатку, и это сработало отлично для меня.

Ответ 9

Это сообщение может появляться, когда веб-сайт защищен с помощью HSTS. Затем, когда кто-то ссылается на HTTP-версию URL-адреса, браузер, как указано HSTS, не выдает HTTP-запрос, а внутренне перенаправляет на HTTPS-ресурс. Это делается для того, чтобы избежать атак с понижением HTTPS, таких как sslstrip.

Ответ 10

Это может произойти из-за того, что вы отправили запрос Ajax, и в то же время вы перешли на другую страницу, используя location.href или что-то в этом роде. Так что предыдущий запрос не удался.

Ответ 11

Это предупреждение также возникает, если ответ недействителен и поэтому брошен браузером.

В моем случае запрос был правильно отправлен на сервер, тогда код на стороне сервера выдал ошибку, и моя пользовательская обработка ошибок вернула сообщение об ошибке в поле сообщения HTTP-статуса. Но эта ошибка не была получена на стороне клиента из-за недопустимых символов в сообщении об ошибке (здесь описано http://aspnetwebstack.codeplex.com/workitem/1386), что привело к повреждению ответа заголовки.

Ответ 12

Я столкнулся с этой проблемой с вызовом AJAX, который никогда не завершится. Я следил за советом wvega и советом об отладке с chrome://net-internals, чтобы в конечном итоге определить другой обработчик событий click на странице, прослушивание родительского node, заставляя браузер перейти к тому же URL-адресу (так что это было нелегко заметно).

Решение заключалось в том, чтобы добавить event.stopPropagation() в обработчик click на кнопку отправки формы, чтобы не допустить, чтобы щелчок запустил DOM и отменил выполняемый запрос AJAX (инициирован с помощью обработчика submit на form).

Ответ 13

У меня это появилось совсем недавно (сегодня на самом деле), где у меня был вызов AJAX, выходящий на сервер, и Chrome срабатывает «Предупреждение: отображаются предварительные заголовки». В сценариях на стороне сервера PHP есть MySQL-запросы, которые могут быть довольно мгновенными или занимать несколько секунд в зависимости от данного сценария. Ответ моего сервера не отправляется обратно в браузер до тех пор, пока запросы не будут завершены. Я обнаружил, что получаю эту ошибку только в том случае, когда выполняются длительные запросы (до нескольких секунд) и не дают ответа отсылаться обратно.

Мой сценарий включает очень редкую возможность изменить таблицу, добавив/удалив сотни столбцов для вывода погодной модели… следовательно, отставание ответа от итерации через цикл запросов ALTER TABLE.

Ответ 14

Общей причиной этого является то, что вы отслеживаете событие и не предотвращаете действие по умолчанию. Например, если у вас есть событие click, то вы захотите включить:

e.preventDefault();

или

return false;

Если вы этого не сделаете, вы увидите предупреждение предварительных заголовков, а также «отмененный» статус на вкладке «Сеть» на своей веб-консоли.

Ответ 15

В моем случае это был всего лишь ложный путь к ресурсу (svg/img)

Ответ 16

Эта проблема возникла, когда я отправил недопустимый заголовок HTTP-авторизации. Я забыл base64 закодировать его.

Ответ 17

Я наткнулся на это, и он ушел, когда я переключился с https на http. Сертификаты SSL, которые мы используем в dev, не проверяются сторонними лицами. Они только локально созданы dev certs.

Те же звонки отлично работают в Chrome Canary и Firefox. Эти браузеры, похоже, не столь строгие относительно сертификата SSL, как Chrome. Вызовы завершились с ошибкой в ​​Chrome с сообщением «ПРЕДУПРЕЖДЕНИЕ: Предварительные заголовки…».

Я думаю/надеюсь, что когда мы используем законный SSL-сертификат в стадии и prod, мы больше не увидим это поведение в Chrome.

Ответ 18

Я запустил эту проблему, когда попытался загрузить main.js для вызова js во второй раз после внесения изменений в результате ошибки.
Я только что включил «Настройки разработчика» «Отключить кеш (когда DevTools открыт)».
и это сделало очарование.

Ответ 19

Еще один возможный сценарий, который я видел, — тот же самый запрос отправляется снова через несколько миллисекунд (скорее всего, из-за ошибки на стороне клиента).
В этом случае вы также увидите, что статус первого запроса «отменен» и что время ожидания составляет всего несколько миллисекунд.

Ответ 20

Это происходило для меня, когда у меня была ссылка для загрузки, и после нажатия на нее я также пытался поймать клик с помощью jquery и отправить запрос ajax. Проблема заключалась в том, что когда вы нажимаете на ссылку для загрузки, вы покидаете страницу, даже если она не выглядит так. Если файл не будет передан, вы увидите запрошенную страницу. Поэтому я поставил цель = «_ blank» для предотвращения этой проблемы.

Ответ 21

Я получил эту ошибку, когда попытался распечатать страницу во всплывающем окне. Диалоговое окно печати было показано, и оно все еще ожидает моего принятия или отмены печати во всплывающем окне, а на главной странице также ожидалось в фоновом режиме, показывая сообщение ПРЕДОСТЕРЕЖЕНИЕ предварительные заголовки отображаются, когда я пытался щелкнуть другое соединение.

В моем случае решение заключалось в том, чтобы удалить window.print (); script, который он выполнял во <body> всплывающего окна, чтобы предотвратить диалог печати. ​​

Ответ 22

Я видел, что это произошло, когда количество подключений к моему серверу превысило максимальный уровень Chrome max-connections-per-server 6.

Ответ 23

Используйте этот код кода вашего кода:

header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');

Это работает для меня.

Ответ 24

Просто бросаю мои два цента. Я пишу веб-приложение, используя запросы CORS и полный веб-сервис RESTful. Я обнаружил, что хром будет выкидывать эту ошибку, когда у меня есть неполученное исключение или ошибка PHP. Просто запустите кого-нибудь другого в проблему. Я обнаружил, что когда это произойдет, я могу запустить приложение Chrome «Postman — Rest Client» и запустить тот же запрос, но в приложении Chrome я фактически получаю ошибку PHP, которая будет выбрана вместо этой не описательной ошибки.

Ответ 25

Вот еще одно решение.

Если вы столкнулись с этой проблемой при вызове $ajax(), добавьте http://, прежде чем ваш сервер будет решить вашу проблему.

var requestURL = "http://" + serverHost;
$.ajax({
    dataType: "json",
    url: requestURL,
    data: data,
    success: success    
});

Ответ 26

Если вы разрабатываете приложение Asp.Net Mvc и пытаетесь вернуть JsonResult в свой контроллер, добавьте JsonRequestBehavior.AllowGet в метод Json. Это исправило это для меня.

public JsonResult GetTaskSubCategories(int id)
{
    var subcategs = FindSubCategories(id);

    return Json(subcategs, JsonRequestBehavior.AllowGet);  //<-- Notice it has two parameters
}

Ответ 27

«Предупреждение: предварительные заголовки показаны» сообщение может быть показано, когда веб-сайт, размещенный в HTTPS, вызывает вызовы WebApi, размещенные по протоколу HTTP. Вы можете проверить все, если все ваши Api — HTTPS. Браузер предотвращает вызов ненадежного ресурса. Вы можете увидеть подобное сообщение в своем коде, когда используете API FETCH для домена с HTTP.

Смешанный контент: страница с надписью https://website.com ‘была загружена через HTTPS, но запросила небезопасный ресурс’ http://webapi.com ‘. Этот запрос заблокирован; содержимое должно быть передано через HTTPS.

Ответ 28

У меня была аналогичная проблема с моим MEAN-приложением. В моем случае проблема происходила только в одном запросе на получение. Я попытался с удалением adblock, попробовал очистить кеш и пробовал с разными браузерами. Ничего не помогло.

Наконец, я понял, что api пытается вернуть огромный объект JSON. Когда я пытался отправить небольшой объект, он работал нормально. Наконец, я изменил свою реализацию, чтобы вернуть буфер вместо JSON.

Я хочу выразить JS, чтобы вывести ошибку в этом случае.

Ответ 29

Очищенные кэшированные данные из истории браузера работают для меня.

Ответ 30

Эта проблема также возникает при использовании некоторых пакетов, таких как webpack-hot-middleware и одновременно открывающих несколько страниц. webpack-hot-middleware создаст соединение для каждой страницы для прослушивания изменений кода, а затем обновит страницу. Каждый браузер имеет ограничение на max-connections-per-server которое составляет 6 для Chrome, поэтому, если вы уже открыли более 6 страниц в Chrome, новый запрос будет зависеть там, пока вы не закроете некоторые страницы.

Recently I worked on a PHP webservice project and I saw this

in Google chrome browser and Opera browser.
I digged some research on Google and find out mixed responses and at last I got it fixed by removing window.print() in script.
Check out all the fixed Provisional headers are shown answers from stackoverflow.

Few developers say that it is because of Chrome plugins like Adblock and VPN. Anyways check out all the responses.

The resource could be being blocked by an extension (AdBlock in my case).

The message is there because the request to retrieve that resource was never made, so the headers being shown are not the real thing. As explained in the issue you referenced, the real headers are updated when the server responds, but there is no response if the request was blocked.

I believe it happens when the actual request is not sent. Usually happens when you are loading a cached resource.

I had similar problem. I changed my button type=”submit” to type=”button”. It worked for me.

I’ve faced with the same issue while working through VPN. To solve the problem had to change the MTU value.

I encountered this issue, and I managed to identify a specific cause, which isn’t mentioned above either in answers or the question.

I am running a full js stack, angular front end and node back end on SSL, and the API is on a different domain running on port 8081, so I am doing CORS requests and withCredentials as I am dropping a session cookie from the API

So specifically my scenario was: POST request, withCredentials to port 8081 caused the “CAUTION: provisional headers are shown” message in the inspector and also of course blocked the request all together.

My solution was to set up apache to proxy pass the request from the usual SSL port of 443 to the node SSL port of 8081 (node has to be on a higher port as it cannot be ran as root in prod). So I guess Chrome doesn’t like SSL requests to unconventional SSL ports, but perhaps their error message could be more specific.

This caution message also occurs if the response is invalid and therefore dropped by the browser.

In my case the request was correctly sent to the server, the server-side code then produced an error and my custom error handling returned the error message in the HTTP status message field. But this error was not received on the client side, due to invalid characters in the error message (described here http://aspnetwebstack.codeplex.com/workitem/1386) which resulted in corrupt response headers.

I came across this and it went away when I switched from https to http. The SSL certs we use in dev aren’t verified by a 3rd party. They’re just locally generated dev certs.

The same calls work just fine in Chrome Canary and Firefox. These browsers don’t appear to be as strict about the SSL cert as Chrome is. The calls would fail in Chrome with the “CAUTION: Provisional headers…” message.

I think/hope that when we use a legit SSL cert in stage and prod, we won’t see this behavior in Chrome anymore.

I doubt my answer is in time to help you but others might find it helpful. I experienced a similar issue with a jQuery Ajax Post script that i created.

It turned out that i had a typo in the href attribute of the A tag that i was using to fire the post. I had typed href=”javacsript:;” (reversing the ‘s’ and the ‘c’ ).. this caused the script to try to refresh the page while the post was attempting to fire. corrected the typo and it worked perfectly fine for me.

Just throwing in my two cents. I’m writing a Web Application using CORS requests and a full RESTful web service. I have found chrome will throw this error when I have an unhanded exception or a PHP Error thrown. Just incase anyone else runs into the problem. I found that when this happens I can fire up the Chrome App “Postman – Rest Client” and run the exact same request but in the Chrome App I’ll actually get the PHP Error thats being thrown instead of this non descriptive error.

Here is another solution.

If you encounter this issue with $ajax() call, add http:// before your serverhost will solve your problem.

var requestURL = “http://” + serverHost; $.ajax({ dataType: “json”, url: requestURL, data: data, success: success });

I ran into this issue with an AJAX call that would never complete. I followed wvega’s advice and tip about debugging with chrome://net-internals to eventually determine another click event handler in the page, listening on a parent node, was causing the browser to navigate to the same URL (so it wasn’t easily noticeable).

The solution was to add event.stopPropagation() in a click handler on the form submit button to keep the click from bubbling up the DOM and canceling the AJAX request in progress (initiated via a submit handler on the form).

I ran this issue when I tried to load main.js for require js for the second time after I made changes as a result from error . I just turned on in Developer Tools Settings “Disable Cache (When DevTools is Open)” . and that did the charm.

Another possible scenario I’ve seen – the exact same request is being sent again just after few milliseconds (most likely due to a bug in the client side).
In that case you’ll also see that the status of the first request is “canceled” and that the latency is only several milliseconds.

I’ve had this come up very recently (today in fact) where I’ve had an AJAX call go out to the server and Chrome fires off the “Caution: Provisional headers are shown.” In the server side PHP scripting, there are MySQL queries that can be pretty much instant or take a few seconds depending on the given scenario. My server response isn’t sent back to the browser until the queries are completed. I’ve found I get this error only when time consuming queries (up to a few seconds total) are being done and prevent the response from being sent back.

My scenario involves the very rare possibility of having to alter a table by adding/removing hundreds of columns for weather model output…hence the response lag from iterating through a loop of ALTER TABLE queries.

This was happening for me, when I had a download link and after clicking on it I was trying also to catch the click with jquery and send an ajax request. The problem was because when you are clicking on the download link, you are leaving the page, even it does not look so. If there would no file transfer, you would see the requested page.. So I set a target=”_blank” for preventing this issue.

I got this error when I tried to print a page in a popup. The print dialog was show and it still waiting my acceptance or cancellation of the printing in the popup while in the master page also was waiting in the background showing the message CAUTION provisional headers are shown when I tried to click another link.

In my case the solution was to remove the window.print (); script that it was executing on the body tag of the popup window to prevent the print dialog.

A common reason this happens is if you are tracking an event and you don’t prevent the default action. For example, if you have a click event, then you will want to include:

e.preventDefault();
or

return false;
If you don’t, you will see the provisional headers warning as well as a “canceled” status in the Network tab of your web console.

If you are developing an Asp.Net Mvc application and you are trying to return a JsonResult in your controller, make sure you add JsonRequestBehavior.AllowGet to the Json method. That fixed it for me.

public JsonResult GetTaskSubCategories(int id) { var subcategs = FindSubCategories(id); return Json(subcategs, JsonRequestBehavior.AllowGet); //< Notice it has two parameters } When chrome redirect to a new url, some http requests will be canceled immediatly, you will find ‘provisional headers are shown’ in debug console.

Above anwers are took from stackoverflow and other sites for only informational purpose.

Based on your response, I have modified the test case. The request from TestWorker.js is now to a different endpoint that
has NEVER been hit before:

starter.js

// open background page devTools
chrome.developerPrivate.openDevTools({
    renderViewId    : -1,
    renderProcessId : -1,
    extensionId     : chrome.runtime.id
});

// timeout just to let devTools open before making requests
setTimeout(() => {
    fetch('https://reqbin.com/echo/get/json')
        .then(response => response.json())
        .then(response => {
            console.log('background page response', response);
        });

    new Worker('TestWorker.js');
}, 6000)

TestWorker.js

fetch('https://jsonplaceholder.typicode.com/posts/3')
    .then(response => response.json())
    .then(response => {
        console.log('worker response', response);
    });

The problem persists, as the worker request still shows the provisional headers message.

You can see in this screenshot of devTools that the first request is now cached (size column shows «(disk cache)»), as we have made it before. The second request from the worker indicates that it is NOT from cache, as it has the size.
devtools1

Looking at the details for the first request, you will see «Provisional headers are show. Disable cache to see full headers»:
devtools2

Now looking at the details for the second request, we see a slightly different message, «Provisional headers are shown», but nothing about caching:
devtools3

We have also run a proxy to confirm that the worker request is actually going out.

Here is another test case, in which I have turned on the «Disable cache (while DevTools is open)» option in settings. I make the same request twice from the background page, and a third time from the worker:

starter.js

setTimeout(() => {
    fetch('https://reqbin.com/echo/get/json')
        .then(response => response.json())
        .then(response => {
            console.log('background page response 1', response);

            fetch('https://reqbin.com/echo/get/json')
                .then(response => response.json())
                .then(response => {
                    console.log('background page response 2', response);

                    new Worker('TestWorker.js');
                });
        });

}, 3000)

TestWorker.js

fetch('https://reqbin.com/echo/get/json')
    .then(response => response.json())
    .then(response => {
        console.log('worker response', response);
    });

Now, none of the requests show «(disk cache)» in the size column:
devtools4

Details on the background page requests DO NOT show provisional headers warning, as expected:
devtools5

BUT, looking at the details for the request made from the worker, it still shows «Provisional headers are shown»:
devtools6

In conclusion, we are confident the worker request is not cached, yet the provisional headers message is still shown. We are unable to get accurate details on the headers when this message is present.

i have a problem with vue-resource causing a Provisional headers are shown on chrome, using Jquery on the other hand work without any problem

the problem only happens with chrome + vue-resource

Error

Reproduction Link

Chrome 57.0.2987
Windows 7

i dont have adblock or origin installed, and it happen even on guest mode on chrome

a simple call set with setInterval

new Vue({

  el: '#main',

  data: {
    summary: null
  },
        methods: {
            updateSummary: function() {
      /*
                $.post( "summary.php", function( data ) {
                    if(typeof response.body.summary != 'undefined'){
                        this.summary = response.body.summary;
                    }
                });
        */
                this.$http.post('summary.php').then(function(response) {
                    if(typeof response.body.summary != 'undefined'){
                        this.summary = response.body.summary;
                    }
                });
            }
      },
        mounted: function () {
            this.updateSummary();

            setInterval(function () {
                this.updateSummary();
            }.bind(this), 2000);
        }
});

https://jsfiddle.net/7vo2s8z3/1/

Steps to reproduce

usually it happens when i leave the page open for a few hours

What is Expected?

a 200 code response with content served

What is actually happening?

i get a request with these headers

Request URL:http://127.0.0.1:8080/monitor/summary.php
Referrer Policy:no-referrer-when-downgrade
Request Headers

Provisional headers are shown
Accept:application/json, text/plain, /
Content-Type:application/json;charset=utf-8
Origin:http://127.0.0.1:8080
Referer:http://127.0.0.1:8080/monitor/
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36
X-Requested-With:XMLHttpRequest

and looking at chrome://net-internals/#events the cause of failure is

85487: URL_REQUEST
http://127.0.0.1:8080/monitor/summary.php
Start Time: 2017-04-18 09:38:43.826

t=29028 [st= 0] +REQUEST_ALIVE [dt=24184]
—> priority = «MEDIUM»
—> url = «http://127.0.0.1:8080/monitor/summary.php»
t=29029 [st= 1] +DELEGATE_INFO [dt=24183]
—> delegate_blocked_by = «RedirectToFileResourceHandler»
t=53211 [st=24183] CANCELLED
—> net_error = -2 (ERR_FAILED)
t=53212 [st=24184] -REQUEST_ALIVE

Понравилась статья? Поделить с друзьями:
  • Protherm lynx 24 коды ошибок
  • Protherm leopard 24 btv ошибка f7
  • Protherm klom 17 ошибка f01
  • Protherm jaguar 24 ошибка f07
  • Protherm jaguar 24 ошибка f05