ㅡichael
ㅡichael

Reputation: 23

Nuxt.js - ssr, Error Cannot set headers after they are sent to the client

I am having this problem in nuxt.js-ssr environment.

 ERROR  Cannot set headers after they are sent to the client  
   at ServerResponse.setHeader (_http_outgoing.js:535:11)
   at p (node_modules/cookie-universal/dist/cookie-universal-common.js:1:1399)
   at Object.set (node_modules/cookie-universal/dist/cookie-universal-common.js:1:1836)
   at pages/index.js:145:21
   at processTicksAndRejections (internal/process/task_queues.js:97:5)

The reason? Occurs when nuxt fetch(SSR) calls API and writes cookie information in response

protected async fetch() {
  axios.get('https://api.onstove.com/test/test')
  .then((value: AxiosResponse<Test>) => {
      console.log('data ::', value.data);
  })
  .then(() => {
      console.log('cookie before ===> ', this.$cookies.get('T1'));
      this.$cookies.set('T1', 'test122sdfdsfsfds34342');
      console.log('cookie after ===> ', this.$cookies.get('T1'));
  });

}

Let me know if anyone solved it.

Upvotes: 1

Views: 9714

Answers (1)

Borjante
Borjante

Reputation: 10507

If you return the promise nuxt will wait for it to be resolved before sending data to client.

protected async fetch() {
  return axios.get('https://api.onstove.com/test/test')
      .then((value: AxiosResponse<Test>) => {
          console.log('data ::', value.data);
      })
      .then(() => {
          console.log('cookie before ===> ', this.$cookies.get('T1'));
          this.$cookies.set('T1', 'test122sdfdsfsfds34342');
          console.log('cookie after ===> ', this.$cookies.get('T1'));
      });

}

Upvotes: 4

Related Questions