2

I am trying to send two cookies using Fetch in Javascript. This is my function:

var cid_and_auth = process.argv[2];
const fetch = require("node-fetch");


function usePairService()
{
    cid = cid_and_auth.split(" ")[1];
    auth = cid_and_auth.split(" ")[0];
    (async () => {
        await fetch(AUTHENTICATIONURL, {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': CONTENTTYPE,
                'wpay-meta': userPairwpaymeta,
                'cookie': 'cid'=cid,'auth'= auth,
            },
            body: JsonBody,
        })
        });;

}

I am trying to send cookies in the header, but it's giving an error, saying invalid left-hand die in expression. Any help will be appreciated.

5
  • 3
    'cid'=cid tries to assign the value of cid to the string value 'cid'. You cannot assign to a string, hence the error. Commented May 26, 2021 at 21:37
  • try 'cookie': `'cid'=${cid},'auth'= ${auth}`, use back ticks. read more about string literals Commented May 26, 2021 at 21:44
  • @FelixKling any idea how the syntax will be? I am trying to assign cid and auth to cookies. Commented May 26, 2021 at 21:45
  • @NeelDebnath I did this: 'cookie': 'cid'=${cid},'auth'= ${auth}. Not working, its showing expression expected. Commented May 26, 2021 at 21:47
  • Please check I have added back tick in the beginning and at the end of the code or check Felix's ans @Nilu Commented May 26, 2021 at 21:48

1 Answer 1

2

'cid'=cid tries to assign the value of cid to the string value 'cid'. You cannot assign to a string, hence the error.

You have to build up a string of <key>=<value>; pairs. If you have each value in a variable you can either manually build the string, e.g. using template literals:

{
  // ...
  Cookie: `cid=${cid};auth=${auth}`,
 }

or you could create an object from those variables and programmatically create the string (which makes it a bit easier to add more values later on):

const cookieData = {cid, auth};
// ...
{
  // ...
  Cookie: Object.entries(cookieData)
    .map(([key, value]) => `${key}=${value}`)
    .join(';'),
}
Sign up to request clarification or add additional context in comments.

1 Comment

FYI - You might want to use encodeURIComponent on the key and value incase they include = or ; symbols.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.