首页 > 解决方案 > 在 fetch 请求上发送 cookie 和 API Key

问题描述

我正在向 API 发送 GET 请求。浏览器必须在获取请求上发送一个 cookie 和一个 API 密钥

我面临的问题如下:

  1. 如果我在标头上没有 API 密钥的情况下发送请求,则会在请求中发送 cookie
fetch(urlToRequest, {
    method: "GET",
    mode: "cors",
    credentials: "include"
})
    .then((response) => {
        console.log(response);
    })
    .catch ((error) => {
        console.log(error)
    });
  1. 如果我包含带有 API 密钥的标头,则不会在请求中发送 cookie
fetch(urlToRequest, {
    method: "GET",
    mode: "cors",
    credentials: "include",
    headers: {"api-key": apiKey}
})
    .then((response) => {
        console.log(response);
    })
    .catch ((error) => {
        console.log(error)
    });

这种行为正常吗?浏览器不应该发送cookie和api密钥吗?

标签: javascriptapicookiesfetch

解决方案


这是 Chrome 的问题,在某些情况下 Chrome 调试器不显示 cookie。我想 cookie 已发送。


推荐阅读