JavaScript中如何通过XMLHttpRequest获取Cookie内的AccessToken用于REST接口认证?
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.
1. First: Verify the AccessToken Cookie Actually Exists
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 aSet-Cookiefield)
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
3. Why Your GET Request Still Fails: Sending the Cookie with Requests
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-Originheader 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

