如何应用getCookie函数正确获取Cookie值,解决地图标记显示异常?
Got it, let's break down what's causing the "phone number undefined" issue and how to use that getCookie function properly.
The Root Problem
When you set your cookie, you're only storing the phone number value without a key/name for it. The document.cookie string stores all cookies in a key=value; key2=value2 format—so right now, your cookie is just floating there without a label, which makes it impossible for the getCookie function to target it. Plus, if there are other cookies present, reading document.cookie directly will return all of them mashed together, leading to that messy undefined message.
Step 1: Fix How You Set the Cookie
First, update your cookie-setting code to include a clear key (we'll use phoneNumber as an example) and add basic cookie attributes (like a path to ensure it's accessible across your app, and an expiration date so it doesn't disappear when the session ends):
// Get the user's phone number with a safety check for null user const userPhoneNumber = firebase.auth().currentUser?.phoneNumber || ""; // Set cookie with a key, value, and essential attributes if (userPhoneNumber) { const daysToExpire = 7; // Keep cookie for 7 days, adjust as needed const expirationDate = new Date(); expirationDate.setTime(expirationDate.getTime() + (daysToExpire * 24 * 60 * 60 * 1000)); document.cookie = `phoneNumber=${userPhoneNumber}; expires=${expirationDate.toUTCString()}; path=/`; } handleSignedInUser(user);
We added optional chaining (?.) to avoid errors if currentUser is null, and wrapped the cookie set in a check to avoid storing empty values.
Step 2: Use the getCookie Function to Read the Value
Now you can use the getCookie function to fetch only the phoneNumber cookie value, instead of reading the entire document.cookie string. Update your marker code like this:
// Use the getCookie function to fetch the specific phone number cookie var markerLabel = getCookie("phoneNumber"); // Fallback if the cookie doesn't exist (avoid undefined in label) if (!markerLabel) { markerLabel = "No phone number available"; } var marker = new google.maps.Marker({ position: { lat: data.User.l[0], lng: data.User.l[1] }, map: map, label: markerLabel });
How the getCookie Function Works
Just to clarify: the function takes a cookie name (cname), searches the decoded document.cookie string for that name followed by =, then extracts the value after that. By targeting the phoneNumber key we set earlier, it will only return the phone number (or an empty string if it can't find it).
Bonus: Debugging Tips
If you still run into issues, open your browser's DevTools (Application tab > Cookies) to check:
- Is the
phoneNumbercookie actually being stored? - Does it have the correct value and expiration date?
- Is the path set correctly (so it's accessible on the page where you're rendering the map)?
内容的提问来源于stack exchange,提问作者BIlly BOB

