首页 > 解决方案 > Nuxt.js - ssr,错误在将标头发送到客户端后无法设置标头

问题描述

我在 nuxt.js-ssr 环境中遇到了这个问题。

 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)

原因?当 nuxt fetch(SSR) 调用 API 并写入 cookie 信息作为响应时发生

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'));
  });

}

让我知道是否有人解决了它。

标签: nuxt.js

解决方案


如果您返回承诺,nuxt 将在向客户端发送数据之前等待它被解析。

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'));
      });

}


推荐阅读