1
const express = require('express');
const config = require('config');
const mongoose = require('mongoose');
const cors = require('cors');
const bodyParser = require('body-parser');
const app = express();
const expressWs = require('express-ws')(app);
const path = require('path');
const fs = require('fs');

app.ws('*', function(ws, req) {
  ws.send('q')
});

const jsonParser = bodyParser.json()

const key = fs.readFileSync('ssl/private.key');
const cert = fs.readFileSync('ssl/certificate.crt');
const ca = fs.readFileSync('ssl/ca_bundle.crt');

const options = {
  key: key,
  cert: cert,
  ca: ca
}

const https = require('https');

https.createServer(options, app).listen(443)
app.use(cors());

app.use(function(req, res, next) {
  if (req.secure) {
    next();
  } else {
    res.redirect('https://' + req.headers.host + req.url);
  }
});

if (process.env.NODE_ENV === 'production') {
  app.use('/', express.static(path.join(__dirname, 'client', 'build')));

  app.get('*', (req, res) => {
    res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'))
  })
}

const PORT = config.get('port') || 5000;

async function start() {
  try {
    await mongoose.connect(config.get('mongoURI'), {
      useNewUrlParser: true,
      useUnifiedTopology: true,
      useCreateIndex: true
    });
    app.listen(PORT, () => console.log(`App has been started on port ${PORT}...`));
  } catch (e) {
    console.log('Server Error', e.message);
    process.exit(1);
  }
}

start();

Клиент: const ws = new WebSocket("ws://example.ru") (вырвал куски кода, что бы не выкладывать тут полотно, вроде бы все нужное для моего вопроса взял) Суть: в юзер скрипте на чужом сайте хочу подключить соединение через веб сокеты. Приведенный код работает для http, но браузер ругается на миксед контент и поэтому приходится подключаться на клиенте через wss, но в таком случае сервер возвращает ошибку: Error during WebSocket handshake: Unexpected response code: 200. Я так понимаю это именно потому, что у меня ws подключение на сервере через https, но я не сильно что то понимаю в ноде и поэтому прошу помощи. Как мне настроить правильно всс соединение?

1 ответ 1

0

Не правильно

const expressWs = require('express-ws')(app);

Правильно

const https     = require('https')
const fs        = require('fs')
const express   = require('express')
const expressWs = require('express-ws')

const serverOptions = {
  key: fs.readFileSync('key.pem'),
  cert: fs.readFileSync('cert.pem'),
  ...
}

const app       = express()
const server    = https.createServer(serverOptions, app)

expressWs(app, server)

app.ws('/echo', (ws, req) => {
    ws.on('message', msg => {
        ws.send(msg)
    })

    ws.on('close', () => {
        console.log('WebSocket was closed')
    })
})

server.listen(443)

Обратите внимание 1:

expressWs(app, server)

Обратите внимание 2:

В репе последний коммит в 2018 году, в issues This project seems to be dead #135 и множество жалоб на неработоспособность в связке с новыми версиями . Я бы такой пакет не использовал.

Обратите внимание 3:

https://www.npmjs.com/package/ws

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.