代码之家  ›  专栏  ›  技术社区  ›  JBrown

POST请求在发送之前无法访问cookie

  •  0
  • JBrown  · 技术社区  · 3 年前

    我通过jQuery POST请求发送了以下数据:

    let eventData = {
      user_id: getCookie('user_id'),
      // some other data...
    };
    
    $.post(someURL, eventData)
    

    用户的唯一id被存储为cookie,并通过以下方式获取 getCookie() 方法:

    const getCookie = cname => {
      if (typeof document !== `undefined`) {
        let name = cname + '=';
        let decodedCookie = decodeURIComponent(document.cookie);
        let allCookies = decodedCookie.split(';');
        let foundCookie = '';
        allCookies.forEach(cookie => {
          if (cookie.includes(name)) {
            foundCookie = cookie.split('=')[1];
          }
        });
        return foundCookie;
      }
    
      return '';
    };
    

    我已经确认cookie存储正确 getCookie() 作品

    奇怪的是,这些请求中大约有2-5%失败,因为 user_id 在中发送 eventData 在后端上不存在。我花了几个小时进行故障排除,认为这可能与 getCookie() 延迟

    在格式化数据(并调用 getCookie() )。有没有可能在某个时间发送请求之前没有返回cookie?它至少95%的时间都有效,所以我很困惑。任何帮助都将不胜感激!

    0 回复  |  直到 3 年前