記一次socket.io的debug記錄
背景:
專案開發客服聊天系統,使用socket.io進行開發,前端採用vue-element-admin,後端語言php,專案在本地執行功能正常,但是釋出到測試環境的時候,socket的連線一直不成功,可以成功返回socketid,但是請求時並沒有將sid作為引數進行請求。
解決過程:
1.首先從socket建立連線開始入手,連線是可以成功的,而且返回值也正常,
2.然後對比socket client和socket server的版本,版本一致,
3. 前專案使用的是-socket.io.js,新專案則採用npm載入的socker.js,為了排除兩者之間的不同,將js替換為本地引入的js,問題也沒有得到解決,
4.檢視polling-xhr.js,確定request的引數,發現是在兩個環境的引數不一致,
1 XHR.prototype.request = function (opts) { 2 opts = opts || {}; 3 opts.uri = this.uri(); 4 opts.xd = this.xd; 5 opts.xs = this.xs; 6 opts.agent = this.agent || false; 7 opts.supportsBinary = this.supportsBinary; 8 opts.enablesXDR = thisView Code.enablesXDR; 9 opts.withCredentials = this.withCredentials; 10 11 // SSL options for Node.js client 12 opts.pfx = this.pfx; 13 opts.key = this.key; 14 opts.passphrase = this.passphrase; 15 opts.cert = this.cert; 16 opts.ca = this.ca; 17 opts.ciphers = this.ciphers; 18 opts.rejectUnauthorized = this.rejectUnauthorized; 19 opts.requestTimeout = this.requestTimeout; 20 21 // other options for Node.js client 22 opts.extraHeaders = this.extraHeaders; 23 console.log('prototype.opts',opts); 24 return new Request(opts); 25 };
5.繼續尋找引數來源的問題,發現mock/index.js中有處理引數的部分,
1 export function mockXHR() { 2 // mock patch 3 // https://github.com/nuysoft/Mock/issues/300 4 Mock.XHR.prototype.proxy_send = Mock.XHR.prototype.send 5 console.log('Mock.XHR.prototype.proxy_send',Mock.XHR.prototype.proxy_send); 6 Mock.XHR.prototype.send = function() { 7 console.log('custom.xhr',this.custom.xhr); 8 console.log('responseType',this.responseType); 9 console.log('...arguments',...arguments); 10 if (this.custom.xhr) { 11 12 this.custom.xhr.withCredentials = this.withCredentials || false 13 14 if (this.responseType) { 15 this.custom.xhr.responseType = this.responseType 16 } 17 } 18 this.proxy_send(...arguments) 19 }View Code
6.由於mockXHR為export function,尋找使用mockXHR的檔案,最終在src/main.js中找到了原因,
import { mockXHR } from '../mock'; if (process.env.NODE_ENV === 'production') { mockXHR(); }View Code
7.此處為vue-element-admin的說明,
- Mock.js
When we useMock.js
to simulate data locally, the real-world api method is used online. This is similar to the easy-mock method above. We mainly judge that when it is an online environment, we use real-world api. We only importMock.js
locally.
// main.js // use environment variables to determine is required if (process.env.NODE_ENV === 'development') { require('./mock') // simulation data }
Mock data is only import in the local environment.
由此可見,是專案前端將mock的引入場景判斷寫為了生產環境,導致了socket的引數被處理,無法正常建立連線,至此暫時告一段落。
後記:這個坑找了好久,頭髮最起碼消耗了86根,希望大家在使用第三方庫的時候,一定要看好文件