سؤال

Note: My question may be very similar to this question, but the solution is not working for me.

My problem is the same as the original poster. I need to access an external resource, and I need to proxy to it to get around cross domain security restrictions. I had also referenced this sample blog post: http://nthloop.com/blog/local-dev-with-nodejs-proxy/

The proxy is working to load external resources (anything containing 'cgi' in the url). But with this code, I am no logner able to hit local (static) files with the connect module. Times out, no error messages, etc...

I am posting the full code of my server.js file:

var httpProxy = require('http-proxy');
var connect = require('connect');
var endpoint  = {
      host:   '11.0.0.120',
      port:   8081
    };

var proxy = new httpProxy.RoutingProxy();
var app = connect()
    .use(function(req, res) {
        if (req.url.indexOf('cgi') >= 0) {
            proxy.proxyRequest(req, res, endpoint);
        } else {connect.static(__dirname)};
    })
    .use(connect.static(__dirname))
    .listen(8182);

This question's solution seemed to state that I needed to include an else condition. It doesn't wok without or without one.

Thanks for any help!

هل كانت مفيدة؟

المحلول

You can use next() to let request flow to the next middleware -

var app = connect()
    .use(function(req, res, next) {
        if (req.url.indexOf('cgi') >= 0) {
            proxy.proxyRequest(req, res, endpoint);
        } else {
            next();
        )};
    })
    .use(connect.static(__dirname))
    .listen(8182);

نصائح أخرى

Oops, got it working just by swapping the use(connect...) function to the first call. Don't know why this worked or if it is the best approach. Also, didn't need the else statement.

If someone can give a better explanation I can accept their answer. Here's my working code:

var httpProxy = require('http-proxy');
var connect = require('connect');
var endpoint  = {
      host:   '11.0.0.120',
      port:   8081
    };

var proxy = new httpProxy.RoutingProxy();
var app = connect()
    .use(connect.static(__dirname))
    .use(function(req, res) {
        if (req.url.indexOf('cgi') >= 0) {
            proxy.proxyRequest(req, res, endpoint);
        }
    })
    .listen(8182);
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top