NodeJS reverse proxy websocket

If you need to reprint, please indicate the source: http://blog.csdn.net/itas109
QQ technical exchange group: 129518033

Article directory
NodeJS reverse proxy websocket
@ [toc]
Foreword
code
related issues:
1.http and websocket different ports expose a port
2.nodejs reverse proxy

Related articles:
NodeJS combined with express using websocket

Foreword
Although Nginx can perform reverse proxy, it does not have a good fit with the developer code. Especially when the front end accesses the port, there may be a problem that the Nginx sets a reverse proxy and does not match the program (such as the front end The code does not use the URL port for access). And multiple ports will bring Nginx maintenance costs. In the article of NodeJS and express using websocket, you can combine http and ws ports, but sometimes you need to use two ports, http and ws, respectively. This article will introduce how to reverse proxy at the nodejs code level

代码
const express = require('express');
const proxy = require('http-proxy-middleware');
const app = express();

// var express = require('express');
// var http = require('http');
let https = require("https");
var expressWs = require('express-ws');
var fs = require('fs');

var option = {
key: fs.readFileSync('./keys/private.key'),
ca: fs.readFileSync('./keys/csr.pem'),
cert: fs.readFileSync('./keys/file.crt')
}

app.get('/', function (res, req) {
req.send('123')
})

var wsProxy = proxy ({
target: 'https: // localhost: 8080', // target host
changeOrigin: true, // requires virtual host site
ws: true, // whether to proxy websocket
}); // turn on the proxy function, And load the configuration

// Reverse proxy (here you can configure the path to be reversed here)
// eg: proxy / api / test to $ {HOST} / api / test
app.use ('/ test', wsProxy) ;

serverProxy = https.createServer (option, app);
// listening port

serverProxy.listen(8888, () => {
console.log(`server running`);
});

serverProxy.on('upgrade', wsProxy.upgrade); // -- subscribe to http 'upgrade'

var app2 = express ();

var httpServer;
// httpServer = http.createServer(app2);
httpServer = https.createServer(option, app2);

expressWs(app2, httpServer);

app2.ws ('/ test', function (ws, req) {
console.log ("ok")
ws.send ('You connected successfully')
ws.on ('message', function (msg) {
// Business code
console.log (msg);
ws.send (msg)
})
})

app2.get('/', function (res, req) {
req.send('123')
})

// app.listen (8080);
// httpServer.listen (8080);
httpServer.listen (8080);
————————————————
Copyright Notice: This article is a CSDN blogger The original article of "itas109" follows the CC 4.0 BY-SA copyright agreement. For reprinting, please attach the original source link and this statement.
Original link: https://blog.csdn.net/itas109/java/article/details/104034178

Guess you like

Origin www.cnblogs.com/xiami2046/p/12677075.html