ionic2 app中的Websocket连接错误

时间:2017-11-26 10:11:48

标签: angular websocket ionic2

我正在尝试使用Ionic2和Angular 2构建混合应用程序。 在第一次运行应用程序时出现错误

  

SecurityError:操作不安全。

所以我在 ion-dev.js 文件中将ws更改为wss

this.socket = new WebSocket('ws://' + window.location.hostname + ':' + IonicDevServerConfig.wsPort);

现在我收到错误

  

Firefox无法在wss:// ...

建立与服务器的连接

1 个答案:

答案 0 :(得分:0)

我有类似的问题(Heroku,Angular用于前端,Node.js Web套接字服务器)

最近对我有用的是: 的OnInit

this.http.get(this.portURL)
      .toPromise()
      .then((res: any) => {
        const json = res.json();
        this.port = json.port;
        console.log(`port ${this.port}`);

        this.url = location.origin.replace(/^http/, 'ws');
        if (location.origin.includes('localhost')) {
          this.url = this.url.replace('4200', '5000');
        } else {
          this.url = this.url.replace('4200', this.port.toString());
        }

        this.initWebSocketConnection();
        console.log(`url ${this.url}`);
      })
      .catch((reason) => {
        console.log(reason);
      });

在node.js

const express = require('express');
const socketIO = require('socket.io');
const port = process.env.PORT || 5000;
...
const server = express().get('/port', (req, res) => {
    res.json({port: port})
  })
.listen(port, () => {
    console.log(`Listening on ${port}`)
  });
...

const io = socketIO(server);

io.on(// io staff here ... )

通过这种方式,我设法在本地运行node.js应用程序并在本地运行角度。我的文件结构是这样的:root项目是一个简单的node.js-express应用程序,里面有一个包含角度应用程序的视图文件夹。