天天看點

微信公衆号開發 - 消息回複時報錯 Cannot set headers after they are sent to the client微信公衆号開發 - 消息回複時報錯 Cannot set headers after they are sent to the client

微信公衆号開發 - 消息回複時報錯 Cannot set headers after they are sent to the client

在學習尚矽谷官方的公衆号開發教程時遇到一個問題,就是在消息回複時出現了

(node:15724) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

百度搜尋出來的全是無關問題,改用google一搜就搜出來了,還知道前因後果

搜尋引擎優略可見一斑

解決方法帖:https://stackoverflow.com/questions/7042340/error-cant-set-headers-after-they-are-sent-to-the-client

原因:

在你的事件處理時,多次使用res.send()

res.send()會标記結束請求,再次send時,無法設定響應内容,就會報錯

解決:

你大可以查查你的校驗伺服器邏輯

微信伺服器确認時才需要響應echostr,當微信校驗成功後也就是比對伺服器成功後,就不需要auth.js執行了

此時這段res.send(echostr)就可以不需要了,去掉後,微信回複就可以正常回複了

async (req, res, next)=>{
    // signature: 'b1e3d6d92110f65477feebf691e971008af5c197',
    // echostr: '319786224577051620',
    // timestamp: '1592789988',
    // nonce: '710866606'
    const {signature, echostr, timestamp, nonce} = req.query
    const token = config.token
    const arr = [token, timestamp, nonce]
    arrSort = arr.sort()
    str = arrSort.join('')
    if(signature === sha1(str)){
      console.log('伺服器驗證通過')
      // 此時send已經标記響應成功
      res.send(echostr)
    } else{
      res.end('error')
    }
    next()
  }
           

繼續閱讀