Ember CLI with Multiple Proxies

2019-03-27 06:01发布

问题:

The Problem:

I have an Ember CLI Application that will consume multiple APIs, which I need to proxy to in development mode.

Background:

I have a legacy api which exposes services at /api running on my local development machine at localhost:3000

I have a new api which exposes services at /myapp/api/v1. These services were recently extracted from the legacy app, and comprises the majority of the application services used by the ember app.

The ember app uses the baseURL of /myapp, as it is being deployed to a subdirectory.

I generated two http-proxys using ember generate http-proxy. They are located at /server/proxies/api.js and server/proxies/myapp/api/v1.js

api.js

var proxyPath = '/api';
module.exports = function(app) {
  var proxy = require('http-proxy').createProxyServer({});
  proxy.on('error', function(err, req) {
    console.error(err, req.url);
  });
  app.use(proxyPath, function(req, res, next){
    // include root path in proxied request
    req.url = proxyPath + '/' + req.url;
    proxy.web(req, res, { target: 'http://localhost:3000' });
  });
};

myapp/api/v1.js

var proxyPath = 'myapp/api/v1';
module.exports = function(app) {
  var proxy = require('http-proxy').createProxyServer({});
  proxy.on('error', function(err, req) {
    console.error(err, req.url);
  });
  app.use(proxyPath, function(req, res, next){
    req.url = proxyPath + '/' + req.url;
    proxy.web(req, res, { target: 'http://localhost:4100' });
  });
};

The first proxy, to /api, appears to be working, the second API, to /myapp/api/v1/whatever fails.

It doesn't appear to be used or considered. When I run , for instance a POST to myapp/api/v1/sessions, it just says cannot POST. When I put debugger on the proxy.on and app.use functions, they are never hit.

Where am I going wrong here?

回答1:

var proxyPath = 'myapp/api/v1';

You're missing a / in the beginning of the string ;)