'How to proxy/forward backend API request for PRODUCTION?

Angular v12 needs to send request to an existing API backend, say localhost:4200/post1 to be https://backend/api/post1. proxy.conf.js makes that happen for localhost DEV server when ng serve.

Build and deployed to PROD server, request to API always get 404. POST https://prod/post1 404. Based on Angular Proxying to a backend server, proxy.conf.js is for DEV server running ng serve only, this is confirmed by many others. But in the same doc Rewrite the URL path, it also introduces pathRewrite to rewrite the URL path at run time, an example given is to remove "api".

Confusing but assume pathRewrite does help for PROD run time, instead of removing "api", I want to give a new full URL: /post1 to https://backend/api/post1?

This is my current proxy.conf.js getting 404 at PROD server:

const PROXY_CONFIG = 
[
    {
        context: 
        [
            "/post1"
        ],

        "target" : "https://backend/api",     // so "localhost:4200/post1" forward to "https://backend/api"
        "changeOrigin": true,       
        "pathRewrite": { ??? : ??? }    // how to implement in place of ???
    }
]
module.exports = PROXY_CONFIG;


Solution 1:[1]

Production

You should be setting a reverse proxy in your http server (Apache/Nginx).

Here's an example with Nginx (location answer your question), create a file /etc/nginx/conf.d/example.com.conf:

server {
    listen         80;
    listen         [::]:80;
    server_name    example.com www.example.com;
    root           /var/www/example.com;
    index          index.html;
    try_files $uri $uri/ /index.html;

    location /api/ {
      proxy_pass http://127.0.0.1:3000;
    }
}

Here you can find additional informations: Angular Doc

Developpement

For development, you should create a proxy.conf.json file:

{
  "/api": {
    "target": "http://localhost:3000",
    "secure": false
  }
}

Then you should change npm start command in your package.json:

"start": "ng serve  --proxy-config proxy.conf.json",

Here you can find additional informations: Angular Doc

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1