whatwg-fetch 为什么在预检中不包含凭据(选项)

whatwg-fetch why isn't credentials included while in preflight (OPTIONS)

本文关键字:包含凭 选项 为什么 whatwg-fetch      更新时间:2023-09-26

我正在尝试whatwg-fetch(用于Fetch API的polyfill),并且在进行POST时,会执行预检。但是,由于将 OPTIONS 发送到 REST 服务时未发送凭据,因此我收到"未经授权"的响应。

return fetch('http://localhost:8080/activity', {
  credentials: 'include',
  method: 'POST',
  mode: 'cors',
  body: JSON.stringify(activity),
  headers: new Headers({ 'Content-Type': 'application/json' })
});

以我的情况为例。我相信它会帮助你:

export function doSearchRequest (filters) {
    let token = $('meta[name="csrf-token"]').attr('content');
    return (fetch('/services/search/message', { 
            method: "POST",
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
                'Cache': 'no-cache',
                '_token' : token,
                'X-CSRF-Token' : token,
                'X-XSRF-TOKEN' : token
            },
            credentials: 'include',
            body: JSON.stringify(filters)
        })
        .then(response => response.json())
        .then(function(json) {
            return json;
        })
    );    
}

以下是有关您的案例的所有信息 https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request 也在这里 https://fetch.spec.whatwg.org/#cors-preflight-fetch 。浏览器发送预检选项请求,因为您使用跨域请求