Search code examples
node.jsangularproxyuniversal

proxy in angular universal


I'm on the projects that were made with Angular Universal.

I need to change blog.mywebsite.com to mywebsite.com/blog for SEO, I used proxy-config in ng start, like code below, it works correctly but it doesn't work when I run build:ssr

there is no error in the built project, just after running with node dist / server.js show website but I call mywebsite.com / mag I redirect to 404 page, while there is no problem in npm start

  "scripts": {
   "ng": "ng",
   "build": "ng build --prod",
   "start": "ng serve -o  --proxy-config src/proxy.conf.json ",
   "extract": "ng xi18n --output-path=locale",
   "build:ssr": "npm run build:client-and-server-bundles  && npm run 
    webpack:server ",
   "serve:ssr": "node dist/server.js",
   "build:client-and-server-bundles": "ng build --prod && ng run 
     angular.io-example:server",
  "webpack:server": "webpack --config webpack.server.config.js --devServer -- 
   progress --colors"
  }, 

and this is my config-proxy-file:

  {
    "/mag": {
      "target": {
      "host": "mag.mywebsite.com",
      "protocol": "http:",
      "port": 80
     },
     "secure": false,
     "changeOrigin": true,
     "logLevel": "info",
     "pathRewrite": {"^/mag" : ""}
  }
}

Solution

  • You can configure a proxy in the express server of the app. Serving Angular Universal will not use the proxy config that ng serve uses, so it will try to call the relative domain (i.e. localhost and port when running locally). The answer given here explains how to add an express proxy. To summarize:

    In your src/server.ts file, add

    import * as proxy from 'http-proxy-middleware'
    
    const apiProxy = proxy('/api', { target: 'http://localhost:8080' });
    app.use('/api', apiProxy);
    

    Obviously, you will not want to do this when building for production.