如何为使用动态URL路由的节点/反应项目设置gulp browser-sync

时间:2015-04-09 21:10:46

标签: node.js reactjs gulp browser-sync

我正在尝试将BrowserSync添加到react.js节点项目中。我的问题是我的项目通过server.js文件管理url路由,监听端口和mongoose连接,所以很明显当我运行浏览器同步任务并检查localhost url http://localhost:3000时,我得到一个无法获取/ 即可。

有没有办法强制浏览器同步使用我的server.js文件?我应该使用辅助节点服务器或其他东西(如果我这样做,跨浏览器同步如何工作)?我真的迷失了,所见的所有例子都增加了混乱。帮助!

gulp.task('browser-sync', function() {
    browserSync({
        server: {
            baseDir: "./"
        },
        files: [
            'static/**/*.*',
            '!static/js/bundle.js'
        ],
    });
});

1 个答案:

答案 0 :(得分:3)

我们遇到了类似的问题,我们可以通过使用代理中间件(https://www.npmjs.com/package/proxy-middleware)来解决这个问题。 BrowserSync允许您添加中间件,以便您可以处理每个请求。这是我们正在做的一个精简的例子:

var proxy = require('proxy-middleware');
var url = require('url');

// the base url where to forward the requests
var proxyOptions = url.parse('https://appserver:8080/api');
// Which route browserSync should forward to the gateway
proxyOptions.route = '/api'

// so an ajax request to browserSync http://localhost:3000/api/users would be 
// sent via proxy to http://appserver:8080/api/users while letting any requests
// that don't have /api at the beginning of the path fall back to the default behavior.

browserSync({
    // other browserSync options
    // ....
    server: {
        middleware: [
            // proxy /api requests to api gateway
            proxy(proxyOptions)
        ]
    }
});

关于这一点很酷的是,您可以更改代理指向的位置,以便您可以针对不同的环境进行测试。需要注意的一点是,我们所有的路由都以/ api开头,这使得这种方法变得更加容易。挑选和选择要代理的路线会有点棘手,但希望上面的例子能给你一个很好的起点。

另一个选择是使用CORS,但是如果你没有在生产中处理它,那么你的开发环境可能不值得搞乱。