Sec fetch mode что это
Перейти к содержимому

Sec fetch mode что это

  • автор:

Sec-Fetch-Mode

Вообще говоря, это позволяет серверу различать: requests, исходящий от пользователя, перемещающегося между страницами HTML, и requests для загрузки изображений и других ресурсов. Например, этот заголовок будет содержать navigate для навигации верхнего уровня requests, а no-cors используется для загрузки изображения.

Header type Получить заголовок запроса метаданных
Запрещенное имя заголовка да (префикс Sec- )
Заголовок запроса CORS-safelisted no

Syntax

Sec-Fetch-Mode: cors Sec-Fetch-Mode: navigate Sec-Fetch-Mode: no-cors Sec-Fetch-Mode: same-origin Sec-Fetch-Mode: websocket 

Серверы должны игнорировать этот заголовок, если он содержит любое другое значение.

Directives

Примечание. Эти директивы соответствуют значениям в Request.mode .

Запрос является запросом CORS protocol .

Запрос инициируется переходом между документами HTML.

Запрос является запросом без корреспонденции (см. Request.mode ).

Запрос делается из того же источника, что и запрашиваемый ресурс.

Выполняется запрос на установление соединения WebSocket .

Examples

Если пользователь щелкает ссылку страницы на другую страницу в том же источнике, результирующий запрос будет иметь следующие заголовки (обратите внимание, что режим — navigate ):

Sec-Fetch-Dest: document Sec-Fetch-Mode: navigate Sec-Fetch-Site: same-origin Sec-Fetch-User: ?1 
Sec-Fetch-Dest: image Sec-Fetch-Mode: no-cors Sec-Fetch-Site: cross-site

Specifications

Specification
Получение заголовков запроса метаданных # sec-fetch-mode-header

Sec-Fetch-Mode

The Sec-Fetch-Mode fetch metadata request header indicates the mode of the request.

Broadly speaking, this allows a server to distinguish between: requests originating from a user navigating between HTML pages, and requests to load images and other resources. For example, this header would contain navigate for top level navigation requests, while no-cors is used for loading an image.

Header type Fetch Metadata Request Header
Forbidden header name yes (prefix Sec- )
CORS-safelisted request header no

Syntax

Sec-Fetch-Mode: cors Sec-Fetch-Mode: navigate Sec-Fetch-Mode: no-cors Sec-Fetch-Mode: same-origin Sec-Fetch-Mode: websocket 

Servers should ignore this header if it contains any other value.

Directives

Note: These directives correspond to the values in Request.mode .

The request is a CORS protocol request.

The request is initiated by navigation between HTML documents.

The request is a no-cors request (see Request.mode ).

The request is made from the same origin as the resource that is being requested.

The request is being made to establish a WebSocket connection.

Examples

If a user clicks on a page link to another page on the same origin, the resulting request would have the following headers (note that the mode is navigate ):

Sec-Fetch-Dest: document Sec-Fetch-Mode: navigate Sec-Fetch-Site: same-origin Sec-Fetch-User: ?1 
Sec-Fetch-Dest: image Sec-Fetch-Mode: no-cors Sec-Fetch-Site: cross-site 

Specifications

Specification
Fetch Metadata Request Headers
# sec-fetch-mode-header

Browser compatibility

BCD tables only load in the browser

See also

  • Related headers
    • Sec-Fetch-Dest
    • Sec-Fetch-Site
    • Sec-Fetch-User

    Found a content problem with this page?

    • Edit the page on GitHub.
    • Report the content issue.
    • View the source on GitHub.

    This page was last modified on Oct 25, 2023 by MDN contributors.

    Your blueprint for a better internet.

    MDN

    Support

    • Product help
    • Report an issue

    Our communities

    Developers

    • Web Technologies
    • Learn Web Development
    • MDN Plus
    • Hacks Blog
    • Website Privacy Notice
    • Cookies
    • Legal
    • Community Participation Guidelines

    Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
    Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

    Sec-Fetch-Site

    The Sec-Fetch-Site fetch metadata request header indicates the relationship between a request initiator’s origin and the origin of the requested resource.

    In other words, this header tells a server whether a request for a resource is coming from the same origin, the same site, a different site, or is a «user initiated» request. The server can then use this information to decide if the request should be allowed.

    Same-origin requests would usually be allowed by default, but what happens for requests from other origins may further depend on what resource is being requested, or information in other Fetch metadata request headers. By default, requests that are not accepted should be rejected with a 403 response code.

    Header type Fetch Metadata Request Header
    Forbidden header name yes (prefix Sec- )
    CORS-safelisted request header no

    Syntax

    Sec-Fetch-Site: cross-site Sec-Fetch-Site: same-origin Sec-Fetch-Site: same-site Sec-Fetch-Site: none 

    Directives

    The request initiator and the server hosting the resource have a different site (i.e. a request by «potentially-evil.com» for a resource at «example.com»).

    The request initiator and the server hosting the resource have the same origin (same scheme, host and port).

    The request initiator and the server hosting the resource have the same scheme, domain and/or subdomain, but not necessarily the same port.

    This request is a user-originated operation. For example: entering a URL into the address bar, opening a bookmark, or dragging-and-dropping a file into the browser window.

    Examples

    A fetch request to https://mysite.example/foo.json originating from a web page on https://mysite.example (with the same port) is a same-origin request. The browser will generate the Sec-Fetch-Site: same-origin header as shown below, and the server will typically allow the request:

    Sec-Fetch-Dest: empty Sec-Fetch-Mode: cors Sec-Fetch-Site: same-origin 

    A fetch request to the same URL from another site, for example potentially-evil.com , causes the browser to generate a different header (e.g. Sec-Fetch-Site: cross-site ), which the server can choose to accept or reject:

    Sec-Fetch-Dest: empty Sec-Fetch-Mode: cors Sec-Fetch-Site: cross-site 

    Specifications

    Specification
    Fetch Metadata Request Headers
    # sec-fetch-site-header

    Browser compatibility

    BCD tables only load in the browser

    See also

    • Related headers
      • Sec-Fetch-Mode
      • Sec-Fetch-User
      • Sec-Fetch-Dest

      Found a content problem with this page?

      • Edit the page on GitHub.
      • Report the content issue.
      • View the source on GitHub.

      This page was last modified on Oct 25, 2023 by MDN contributors.

      Your blueprint for a better internet.

      MDN

      Support

      • Product help
      • Report an issue

      Our communities

      Developers

      • Web Technologies
      • Learn Web Development
      • MDN Plus
      • Hacks Blog
      • Website Privacy Notice
      • Cookies
      • Legal
      • Community Participation Guidelines

      Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
      Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

      Sec-Fetch-Mode и почему он не везде?

      Если запустить веб сервер встроенный в php командой php -S . и в devtool выполнить команду
      fetch(location.href)
      то на вкладке network -> request headers видим
      Sec-Fetch-Mode: cors
      Sec-Fetch-Site: same-origin
      И такой результат получим и на этом сайте и на гитхабе и на многих других.

      А если зайти на 4pda и выполнить
      fetch(location.href)
      То Sec-Fetch-Mode и Sec-Fetch-Site вообще отсутствуют.

      Заметил это случайно когда увидел что у меня request headers отличается на localhost’e и на vps’ке с запущенным nginx

      Для чего нужны Sec-Fetch-Mode и Sec-Fetch-Site ?
      И почему не на всех сайтах эти заголовки присутствуют?
      И как их добавить?

      • Вопрос задан более трёх лет назад
      • 13961 просмотр

      Комментировать
      Решения вопроса 2

      Они отсутствуют при обращении на http сайты.

      Добавляются автоматически браузером (можно и самому с помощью расширения) при обращении на https сайты.

      В Chromuim’е c 76 версии.

      Реализована поддержка группы HTTP-заголовков Fetch Metadata (Sec-Fetch-Dest, Sec-Fetch-Mode, Sec-Fetch-Site и Sec-Fetch-User), позволяющих отправить дополнительные метаданные о характере запроса (межсайтовый запрос, запрос через тег img и т.п.) для принятия на сервере мер для защиты от некоторых типов атак (например, маловероятно, что ссылка на обработчик для перевода денег будет задана через тег img, поэтому такие запросы можно блокировать без передачи приложению);

      Ответ написан более трёх лет назад
      Комментировать
      Нравится 1 Комментировать

      DevMan

      Для чего нужны Sec-Fetch-Mode и Sec-Fetch-Site ?

      для управления доступом.

      И почему не на всех сайтах эти заголовки присутствуют?

      потому что не везде они нужны. да и использовать их не заставляют.

      И как их добавить?

      Ответ написан более трёх лет назад

      DevMan, куда их добавить?(нужны HTTP_SEC_FETCH_SITE=same_origin, HTTP_SEC_FETCH_MODE=cors, HTTP_SEC_FETCH_DEST=empty)
      в nginx?
      (у меня связка nginx+apache)
      ошибка в браузере
      «ERR_NETWORK» axios

      Ответы на вопрос 0
      Ваш ответ на вопрос

      Войдите, чтобы написать ответ

      веб-разработка

      • Веб-разработка

      Есть ли бесплатные сервисы куда можно выложить свой пет-проект доступный для регистрации пользователям?

      • 6 подписчиков
      • вчера
      • 302 просмотра

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *