Nodejs - BrowserSync running on express server

送分小仙女□ 提交于 2019-12-14 04:22:59

问题


I want to pull a URL from the DB and use it as the proxied URL. However the setup I've come up with initializes a new BrowserSync server for each URL, using incrementing port numbers.

Is there a way to accomplish this without initializing a new BrowserSync server every time?

Or should I be using another approach?

var bs      = require("browser-sync");
var express = require("express");

var router  = express.Router();
var app     = express();

router.get("/", function(req, res){

    var proxyUrl = getUrl() //get url from db (www.example.com)

    bs.create("bs1").init({
        notify: false,
        open: false,
        ui: false,
        port: 10000,
        proxy: proxyUrl
    });
        res.send();
});

app.use(router);

app.listen(8080, function(){
  console.log('listening on *:8080');
});

The above is fine(ish) but is it good practice to be initializing a new server for every URL (potentially thousands)?

And is it safe to be exposing a new port number to every user of the system? (Can I mask this with a subdomain?)

Update

My end goal is to use a unique subdomain to refer to each proxy url.

For example:

sub1.mysite.com proxies www.example.com,

sub2.mysite.com proxies www.example2.com


回答1:


Browser-sync will not work as the proxy is tie to server setup.

I use following packages:

  • express
  • express-http-proxy
  • vhost (express vhost)
const port = 8080;

var app = require('express')();
var proxy = require('express-http-proxy');
var url = require('url');
var vhost = require('vhost');

app.listen(port);

/* Assuming getUrl() will return an array of sites */
// var sites = getUrl();

// DO NOT put '/' at the end of site
var sites = [
    'http://www.bing.com',
    'http://samanthagooden.com',
    'http://www.courtleigh.com'
];

var i = 0;
sites.forEach(site => {
    i++;
    var subDomain = 'sub' + i + '.mysite.com';
    app.use(vhost(subDomain, proxy(site, {
        forwardPath: (req, res) => url.parse(req.url).path,
        intercept: (rsp, data, req, res, callback) => {
            if (res._headers['content-type']) {
                var contentType = res._headers['content-type'];
                if (
                    contentType.indexOf('text') !== -1 ||
                    contentType.indexOf('javascript') !== -1
                ) {
                    // Replace link if content-type = text or javascript
                    var reg = new RegExp(site, 'g');
                    res.send(data.toString().replace(reg, ''));
                } else {
                    res.send(data);
                }
            } else {
                res.send(data);
            }
        }
    })));
    console.log(subDomain + ':' + port + ' proxy: ' + site);
});

The above example will create following proxies:

sub1.mysite.com:8080 proxy: www.bing.com
sub2.mysite.com:8080 proxy: www.example.com



回答2:


Maybe I'm misunderstanding what you are trying to do, but Browsersync and express seems a bit overkill in this case, why not just use node-http-proxy with the native http module?

var http = require('http')
var httpProxy = require('http-proxy')

var options = ...
var proxy = httpProxy.createProxyServer(options)

var server = http.createServer(function (req, res) {
  var proxyUrl = getUrl()
  proxy.web(req, res, { target: proxyUrl })
})

server.listen(8080, function () {
  console.log('listening on *:8080')
})



回答3:


As per me If you want SAAS service using proxy is not the good idea to go is what am thinking.. if you are going with proxy for each client will create process with new port... My Solution is to create node server with listen localhost and map *.domain.com to the server..

If you are using individual database for each client :- in node logic get cname from request host and use that reference to connect database.

Final Controller code would be.. var express = require('express'); var router = express.Router(); var MongoClient = require('mongodb').MongoClient;

/* GET home page. */
router.get('/', function(req, res, next) {
        var client = req.subdomains[0];
        console.log(client);
        MongoClient.connect('mongodb://localhost:27017/'+client, function(err, db) {
  if (err) {
    throw err;
  }
  db.collection('app1').find().toArray(function(err, result) {
    if (err) {
      throw err;
    }
        console.log('data');
    console.log(result);
  });
});

  res.render('index', { title: 'Express' });
});

module.exports = router;
~                                                                                                                                              
~                                  

In future if you get more clients you can implement node cluster or standard Ubuntu cluster using webservice



来源:https://stackoverflow.com/questions/39072317/nodejs-browsersync-running-on-express-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!