簡體   English   中英

Socket.io + NodeJS IONIC CORS 問題

[英]Socket.io + NodeJS IONIC CORS issue

我希望你做得很好。

我目前正面臨我的 IONIC 應用程序的問題。

設置:

  • 安裝了 ngx-socket-io 模塊的 IONIC 5 應用程序
  • NodeJS 后端與 express API 和 socket.io 服務器監聽 xxx.xxx.xxx.xxx:3000
  • socket.io 和 socket.io-client 都在版本 2.4.0

這是我在 IONIC 端使用的代碼:

this._storage.get(`setting:loginToken`).then(setToken => {
      alert("Connecting to socket.io server...")
      this.socket.connect();
      alert("Should be connected...")
      this.socket.emit('authenticate', { token: setToken });
      alert("Auth token sent")
    }, error => console.log(error));

當我使用ionic serve運行應用程序時,這就是我在瀏覽器開發人員工具中得到的:

Blocking a Cross-Origin Request: The "Same Origin" policy does not allow consulting the remote resource located at http://XXX.XXX.XXX.XXX:3000/socket.io/?EIO=3&transport=polling&t=NTkQPqH. Reason: The CORS header "Access-Control-Allow-Origin" is missing.

我在 Android 設備上使用 APK 構建實驗同樣的問題。

但是我對我的快遞 API 的其他“非套接字 io”請求在 IONIC 方面表現良好。

這是我寫的后端代碼:

const app = express();
app.use(cors());

var server = app.listen(config.port, () => {
  console.log('Server is listening on %d in %s mode.', config.port, app.get('env'));
});

var io = require('socket.io')(server)
const socketioJwt = require('socketio-jwt');

io.sockets
  .on('connection', socketioJwt.authorize({
    secret: 'stackoverflow',
    timeout: 15000
  }))
  .on('authenticated', (socket) => {

    socket.on("disconnect", () => {
    })

  });


socket.io-client連接可以很好地模擬客戶端。

在這種情況下會出現什么問題?

感謝您提供的任何幫助或建議。

看起來您需要將 CORS 添加到 io 實例:

對於 v2.xx

require('socket.io')(server, {
  origins: [`http://localhost:${config.port}`]
})

https://socket.io/docs/v2/handling-cors/

對於 v3.xx:

require('socket.io')(server, {
  cors: {
    origin: `http://localhost:${config.port}`,
    methods: ['GET', 'POST']
  }
})

https://socket.io/docs/v3/handling-cors/

我不確定您是否需要 CORS 在 express 應用程序上,因為您似乎只使用 sockets 但這當然取決於您。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM