Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
251 views
in Technique[技术] by (71.8m points)

javascript - How to get specific cookie from Node-Fetch

Is it possible to get a specific cookie from set-cookie in node fetch.js

var ResonseCookies = (SentRequest.headers.raw()['set-cookie']);

and it has returned me as i wanted

[
  'language=en; expires=Tue, 23-Feb-2021 00:55:18 GMT; Max-Age=2592000; path=/; secure; HttpOnly',
  'session.ID=22B9DB6FA61744AC857D417118C7650F; expires=Tue, 23-Feb-2021 00:55:19 GMT; Max-Age=2592000; path=/; secure; HttpOnly',
  'session.present=1; expires=Tue, 23-Feb-2021 00:55:19 GMT; Max-Age=2592000; path=/; secure'
]

is there anyway of just extracting the string 22B9DB6FA61744AC857D417118C7650F From the response.

Thankyou in advance.

question from:https://stackoverflow.com/questions/65866199/how-to-get-specific-cookie-from-node-fetch

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Since cookies are saved all together in a string, you can use methods like split(), find() and startsWith() to get exactly to the cookie key, for example:

const sessionID= document.cookie
.split('; ')
.find(row => row.startsWith('session.ID'))
.split('=')[1];

At the end you will convert the whole string in an array of 2 elements, the key and the value itself, therefore, position [1] in the array.

Another easier way, is to use the npm package doc-cookies. It presents simple methods to set, get and remove cookies, using the syntax:

docCookies.getItem('session.ID')

For setting the cookies in the first place:

docCookies.setItem('session.ID', 'yourCookieValue')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...