Angular app converted @angular/ssr will not proxy requests to existing API

94 views Asked by At

Angular app converted @angular/ssr application to dynamically render pages of type /page/:id and optimize SEO. I have an existing local API made with Go and Gin Routing, and it is running at http://localhost:8081.

I have a server.ts file which was created by @angular/ssr with a proxy middleware from the http-proxy-middleware package. Here is the file:

import 'zone.js/node';

import { APP_BASE_HREF } from '@angular/common';
import { CommonEngine } from '@angular/ssr';
import * as express from 'express';
import { existsSync } from 'node:fs';
import { join } from 'node:path';
import AppServerModule from './src/main.server';
const { createProxyMiddleware } = require('http-proxy-middleware');

// The Express app is exported so that it can be used by serverless Functions.
export function app(): express.Express {
  const server = express();
  const distFolder = join(process.cwd(), 'dist/smartassreviews/browser');
  const indexHtml = existsSync(join(distFolder, 'index.original.html'))
    ? join(distFolder, 'index.original.html')
    : join(distFolder, 'index.html');

  const commonEngine = new CommonEngine();

  server.set('view engine', 'html');
  server.set('views', distFolder);

  // Example Express Rest API endpoints
  // server.get('/api/**', (req, res) => { });
  // Serve static files from /browser
  server.get('*.*', express.static(distFolder, {
    maxAge: '1y'
  }));

  // All regular routes use the Angular engine
  server.get('*', (req, res, next) => {
    const { protocol, originalUrl, baseUrl, headers } = req;

    commonEngine
      .render({
        bootstrap: AppServerModule,
        documentFilePath: indexHtml,
        url: `${protocol}://${headers.host}${originalUrl}`,
        publicPath: distFolder,
        providers: [{ provide: APP_BASE_HREF, useValue: baseUrl }],
      })
      .then((html) => res.send(html))
      .catch((err) => next(err));
  });

  return server;
}

function run(): void {
  const port = process.env['PORT'] || 4000;

  // Start up the Node server
  const server = app();
  const pathFilter = function (path: any, req: any) {
    return path.match('^/api');
  };
  server.use('/api',
    createProxyMiddleware({
      target: 'http://localhost:8081/api',
      pathFilter: pathFilter,
      changeOrigin: true,
      logLevel: 'debug',
      logger: console,
      onProxyReq: function(proxyReq: any, req: any, res: any) {        
          //  log the req
          console.log('RAW REQUEST from the target', JSON.stringify(req.headers));
      },
      onProxyRes: function (proxyRes: any, req: any, res: any) {
      
          //  log the response
          console.log('RAW Response from the target', JSON.stringify(proxyRes.headers));
      }
    }));
  server.listen(port, () => {
    console.log(`Node Express server listening on http://localhost:${port}`);
  });
}

// Webpack will replace 'require' with '__webpack_require__'
// '__non_webpack_require__' is a proxy to Node 'require'
// The below code is to ensure that the server is run only when not requiring the bundle.
declare const __non_webpack_require__: NodeRequire;
const mainModule = __non_webpack_require__.main;
const moduleFilename = mainModule && mainModule.filename || '';
if (moduleFilename === __filename || moduleFilename.includes('iisnode')) {
  run();
}

export default AppServerModule;

As you can see, requests of type "http://localhost:4000/api" should be proxied to "http://localhost:8081/api". However, this is not what happens, in fact my local api does not get any of these requests at all. Instead, I get errors of this type:

ERROR RuntimeError: NG04002: 'api/pages/products'
    at Recognizer.noMatchError (/Users/kacylombard/Desktop/smartassreviews/client/smartassreviews/dist/smartassreviews/server/main.js:1:2773346)

So essentially, my basic API callouts in my Angular components are not working. For example, this callout does not work:

 async ngOnInit() {
    this.spinner.show();
    try {
      const data = await this.exploreService.getAllReviewPages(this.pageNum)

In fact, this API callout returns an entire HTML file representing the current page I'm on, when it's actually supposed to return a list of JSON objects.

0

There are 0 answers