简体   繁体   中英

How to read cookie on Angular2 side (set by the c# server)

I can't figure out how the angular code can read the cookie set on the server side. The code below is taken from GitHub. The function below in written in c# and sets the cookie in Response object by the last line of code. My question is how do I read this cookie on the Angular2 java script side. Can someone point me to the right direction please?

private void setTokenCookie(string token)
{
    var cookieOptions = new CookieOptions
    {
        HttpOnly = true,
        Expires = DateTime.UtcNow.AddDays(7)
    };
    Response.Cookies.Append("refreshToken", token, cookieOptions);
}

Angular does not have native support for Cookies . You need to use either a built-in library for this available on NPM or deal with it simply with JavaScript and browser capability.

Option 1:

You can use angular2-cookie

Option 2:

You can use a method like this (or update it) to meet your need of reading a cookie:

readCookies(){
 let name = name + "="; 
 let cookie_array = document.cookie.split(';'),
 for(var i=0;i<cookie_array.length;i++) {
    let cookie=cookie_array[i];
    while(cookie.charAt(0)==' '){
       cookie = cookie.substring(1,cookie.length);
       if(cookie.indexOf(name)==0){
       return cookie.substring(name.length,cookie.length);
      }
   }
 }
}

I hope this helps point you in the right direction.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM