You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript中如何通过XMLHttpRequest获取Cookie内的AccessToken用于REST接口认证?

Troubleshooting Authenticated API Calls as a JavaScript Newbie

Hey there! Let's work through this issue together—since you've already completed authentication but still get unauthenticated responses, there are a few key things to check, including how to access that AccessToken cookie and ensure it's being sent with your requests.

Before jumping into code, let's confirm the cookie was set correctly. Here's how:

  • Open your browser's Developer Tools (F12 or Ctrl+Shift+I)
  • Go to the Application tab
  • Expand the Cookies section on the left, then select the domain of your authentication API
  • Look for a cookie named AccessToken—if it's not here, your authentication request might not have succeeded as expected (double-check the auth request's response headers for a Set-Cookie field)

2. How to Retrieve the AccessToken from Cookies in JavaScript

If the cookie exists, you can extract its value with a simple helper function. Browsers store cookies as a single string, so we need to parse it:

function getCookie(cookieName) {
  // Split the cookie string and find the target cookie
  const cookieString = `; ${document.cookie}`;
  const cookieParts = cookieString.split(`; ${cookieName}=`);
  
  // If the cookie exists, return its value
  if (cookieParts.length === 2) {
    return cookieParts.pop().split(';').shift();
  }
  
  // Return null if the cookie isn't found
  return null;
}

// Use the function to get your AccessToken
const accessToken = getCookie('AccessToken');
console.log('Retrieved AccessToken:', accessToken); // Check the console to confirm it's not null

Even if you can retrieve the cookie, browsers won't automatically send cookies cross-domain unless you explicitly allow it. Here's how to fix this for common request methods:

Using fetch

Add the credentials: 'include' option to your fetch call—this tells the browser to send cookies along with the request:

fetch('https://your-target-api-url.com/endpoint', {
  method: 'GET',
  credentials: 'include' // Critical for sending cookies cross-domain
})
.then(response => {
  if (!response.ok) {
    throw new Error(`Request failed with status: ${response.status}`);
  }
  return response.json();
})
.then(data => console.log('Success! Response:', data))
.catch(error => console.error('Error:', error));

Using axios

If you're using axios, set the withCredentials: true option instead:

axios.get('https://your-target-api-url.com/endpoint', {
  withCredentials: true
})
.then(response => console.log('Success! Response:', response.data))
.catch(error => console.error('Error:', error));

4. Check for Cross-Origin Resource Sharing (CORS) Issues

If your frontend is hosted on a different domain than the API, the API server must be configured to allow credentials:

  • The server must send the header Access-Control-Allow-Credentials: true
  • The Access-Control-Allow-Origin header cannot be *—it must be set to your exact frontend domain (e.g., https://your-frontend.com)

If these headers aren't present, the browser will block the cookie from being sent, even if you set credentials: 'include'.


内容的提问来源于stack exchange,提问作者pedron

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:50:41