Cannot set headers after they are sent to the client nuxt
背景
- 使用axios在created时请求2个接口,代码如下。
- 然后报错如下:
ERROR Cannot set headers after they are sent to the client 14:54:29
at new NodeError (node:internal/errors:372:5)
at ServerResponse.setHeader (node:_http_outgoing:576:11)
at Storage.setCookie (server.js:3323:20)
at Storage.setUniversal (server.js:3175:10)
at Storage.syncUniversal (server.js:3202:12)
at Token._syncToken (server.js:4046:26)
at Token.sync (server.js:3998:24)
at LocalScheme.check (server.js:4175:30)
at server.js:3934:87
at runMicrotasks (<anonymous>)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
解决方案
- 我查找资料说是发送了多次请求的问题。
- 然后我在created代码块测试。
created() {
// this.initDate();
let random = Math.floor(Math.random()*10+1)
console.log("调用了created ",random);
},
- 果然调用了2次。有一次是nuxt调用的。
方案一
- 后面我改在
mounted
执行了。
mounted() {
console.log("调用了mounted");
this.initDate();
},
方案二
- 判断是否在客户端
created() {
if (process.client) {
let random = Math.floor(Math.random()*10+1)
console.log("调用了created ",random);
// handle client side
this.initDate();
}
},
posted on 2023-01-27 15:07 愤怒的苹果ext 阅读(46) 评论(0) 编辑 收藏 举报 来源