API调用前的Angular Universal server.ts配置代理未重写路径

时间:2019-07-04 17:06:31

标签: angular express proxy angular-universal universal

我正在尝试使用以下命令从Angular Universal Express服务器代理api请求 http-proxy-middleware。但是重写是在我的API调用之后发生的。

加载SSR视图时,我需要动态加载数据。但是我的API在另一台服务器上,因此我需要使用代理。我一直在寻找解决方案,当我在server中应用代理时,很不幸地发现使用http-proxy-middleware的一种解决方案。已经调用了api后,ts的配置路径已被重写。

// These are important and needed before anything else
import 'zone.js/dist/zone-node';
import 'reflect-metadata';
import * as express from 'express';
import * as path from 'path';
import { ngExpressEngine } from '@nguniversal/express-engine';
import { AppServerModuleNgFactory } from './dist/frontend-server/main';
import * as proxy from 'http-proxy-middleware'
const distFolder = path.join(process.cwd(), 'dist', 'frontend');
const MockBrowser = require('mock-browser').mocks.MockBrowser;
const mock = new MockBrowser();

//Angular broking universal stuff
global['navigator'] = mock.getNavigator();
global['document'] = mock.getDocument();
global['window'] = mock.getWindow();
global['location'] = mock.getLocation();
global['history'] = mock.getHistory();
global['localStorage'] = mock.getLocalStorage();
global['sessionStorage'] = mock.getSessionStorage();
Object.defineProperty(document.body.style, 'transform', {
  value: () => {
    return {
      enumerable: true,
      configurable: true
    };
  },
});

//Engine
const app = express();
app.set('view engine', 'html');
app.set('views', distFolder);
app.engine('html', ngExpressEngine({
  bootstrap: AppServerModuleNgFactory
}));
//Proxy
var options = {
  target: 'http://localhost:8080', // target host
  pathRewrite: {
    '^/api': ''
  },
  logLevel: 'debug',
};
var apiProxy = proxy(options);
app.use('/api',apiProxy);

//Routes
app.get('*.*', express.static(distFolder));
app.get('*', (req, res) => {
  res.render('index', { req });
});

app.listen(4200, () => console.log('Running on http://localhost:4200'));
Angular is running in the development mode. Call enableProdMode() to enable the production mode.
data
[Error]
[Error]
[Error]
[HPM] Rewriting path from "/api/public/offer" to "/public/offer"
[HPM] GET /api/public/offer ~> http://localhost:8080

“数据”是我开始订阅的时刻。 [错误]可能是错误的api调用。然后我要申请代理。

我希望在api调用之前将我所有的api请求都进行代理。

0 个答案:

没有答案