meh_programmer meh_programmer - 1 month ago 15
Node.js Question

Koa cookie returning `undefined`

After a POST request is sent from the browser to the

/generate
url in the server, I want to create a string and save it as a cookie. When a GET request is later sent from the browser to the
/retrieve
url in the server, I want to send that string as a response to the client.

Here is what I tried:

routes.js

const Router = require('koa-router')
const router = new Router()

router.post('/generate', function * () {
this.cookies.set('generatedString', 'example')
this.response.body = 'String saved as cookie!'
})

router.get('/retrieve', function * () {
const cookie = this.cookies.get('generatedString')
console.log(cookie) // undefined!
this.response.body = cookie
})


Why does doing
this.cookies.get('generatedString')
return
undefined
even though the POST request handler has already run and should have
set
that cookie? Any help would be appreciated!




EDIT: In case it is of importance, I thought it would be worth mentioning that I am using the
fetch
API to make the POST and GET requests.

Answer

In case it is of importance, I thought it would be worth mentioning that I am using the fetch API to make the POST and GET requests.

The fetch API mentions that "By default, fetch won't send any cookies to the server, resulting in unauthenticated requests if the site relies on maintaining a user session."

If you want fetch to send cookies, you will need to add an option to the request you send out called credentials and set it to a value of include.

Example POST request:

const request = {
  method: 'POST',
  credentials: 'include',
  headers: ...,
  body: ...
}

fetch('/generate', request).then(...)

Example GET request:

fetch('/retrieve', { credentials: 'include' }).then(...)
Comments