简体   繁体   中英

Cannot Set cookie in axios response

I'm using the Nuxt.js to develop the website, I want to call API and put the results to the cookie on server side

I will do this part in Nuxt.js middleware. But I can call API, I can set the cookies, but I CANNOT set cookie using the API response.

Call API

import axios from 'axios'

export default ({ res, store }) => {
  if (process.server) {
    axios.get(process.env.tokenAPI)
      .then((response) => {
        const token = response.data.token
        // console.log(token) and the server console will log the result
      })
  }
}

SET COOKIE

export default ({ res, store }) => {
    res.setHeader('Set-Cookie', [`token=123456`]) // It works!!

}

Combine them

import axios from 'axios'

export default ({ res, store }) => {
  if (process.server) {
    axios.get(process.env.token)
      .then((response) => {
        const token = response.data.token
        res.setHeader('Set-Cookie', [`token=${token}`]) 
      })
  }
}

No cookie is set when I use this code, it should set the cookie from result

Can you try this:

import axios from 'axios'
export default ({ res, store }) => {
  if (process.server) {
    axios.get(process.env.token)
      .then((response) => {
        document.cookie = "token="+response.data.token+"; expires=Thu, 18 Dec 2019 12:00:00 UTC; path=/";
      })
  }
}

It's because the middleware has to wait on sending the response until you set the header.

import axios from 'axios'

export default async ({ res, store }) => {
  if (process.server) {
    const response = await axios.get(process.env.token);
    const token = response.data.token;
    res.setHeader('Set-Cookie', [`token=${token}`]);
  }
}

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