【问题标题】:whatwg-fetch why isn't credentials included while in preflight (OPTIONS)whatwg-fetch 为什么在预检时不包含凭据(选项)
【发布时间】:2016-07-03 22:40:36
【问题描述】:

我正在尝试 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' })
});

【问题讨论】:

  • 如果您控制服务器,则需要配置服务器,使其不需要对OPTIONS 请求进行身份验证(服务器没有理由要求对它们进行身份验证,而不是 @ 987654323@ 或 POST 请求)。但是如果你不控制服务器,浏览器就无法正确地向它发出任何需要 CORS 预检的跨域请求。
  • 对不起,为什么 fetch api 会发送一个 OPTIONS 请求?

标签: javascript rest cors fetch-api


【解决方案1】:

以我的情况作为答案。我相信它会对你有所帮助:

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;
        })
    );    
}

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-07-27
      • 1970-01-01
      • 1970-01-01
      • 2017-08-24
      • 1970-01-01
      • 2016-10-13
      • 2012-09-21
      相关资源
      最近更新 更多