Cannot set headers after they are sent to the client nuxt

background

  • Use axios to request 2 interfaces when created, the code is as follows.

insert image description here
insert image description here

  • Then the error is reported as follows:

 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)

solution

  • I searched for information and said that it was a problem of sending multiple requests.
  • Then I test in the created code block.
  created() {
    
    
    // this.initDate();
    let random = Math.floor(Math.random()*10+1)
    console.log("调用了created ",random);
  },
  • Sure enough, it was called 2 times. Once called by nuxt.
    insert image description here

Option One

  • mountedI changed it to execute later .
  mounted() {
    
    
    console.log("调用了mounted");
    this.initDate();
    
  },

Option II

  • Determine whether the client
created() {
    
    

    if (process.client) {
    
    
      let random = Math.floor(Math.random()*10+1)
      console.log("调用了created ",random);
      // handle client side
      this.initDate();
    }
  },

insert image description here

Guess you like

Origin blog.csdn.net/baidu_19473529/article/details/128770753