Home > Enterprise >  PERN Stack deployment on AWS EC2 Nginx URL issue
PERN Stack deployment on AWS EC2 Nginx URL issue

Time:10-04

Would highly appreciate it if someone could help or point me in the right direction with my issue.

The app works fine localhost but when I deployed to AWS, all the sub-pages gets wrong formatted Axios request URLs. Something must be wrong with either my Nginx config or React app Axios base URL settings but not quite sure how I should set it up.

The API endpoint and client-side baseurl works fine live at: http://app3.dev100.xyz but every sub-page Axios API request gets wrong formatted request URLs, please see the example below.

For example, if I click the product page somehow all the Axios API request gets "products" middle of the URL.
Wrong: http://app3.dev100.xyz/products/api/products/3/related
Correct: http://app3.dev100.xyz/api/products/3/related

Client-side routing is done using react-router history if that makes any difference.

React axios baseurl development and deployed production setup

// Development (works fine localhost)
axios.defaults.baseURL = 'http://localhost:5000/api';

// Deployment (works only for the main domain but not for subpages as explained above)
axios.defaults.baseURL = 'api';

// Original conditional setup was done like this
axios.defaults.baseURL = process.env.NODE_ENV === 'prodcution' ? "api/" : 'http://localhost:5000/api';

Nginx setup. Client and API are hosted on the same server

server {
    listen 80;
    listen [::]:80;

    root /home/ubuntu/apps/ecom-app/client/build;

    # Add index.php to the list if you are using PHP
    index index.html index.htm;

    server_name app3.dev100.xyz;

    location / {
            try_files $uri /index.html;
    }

    location /api/ {
        proxy_pass http://localhost:5000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}

CodePudding user response:

I changed the Axios baseURL to include the domain name from 'api' to 'https://app3.dev100.xyz/api' and that seemed to work.

I didn't develop the client app so not sure what was the original idea using only 'api' as an Axios baseURL. Although I have seen other people use it like that but not sure how they get it to work and how Axios formats the URL.

I'll leave the Axios request and React routing settings here just for the reference.

<Route exact path='/products/:id' component={Product} />
history.push({ pathname: `/products/${slug}`, state: { productId: id } });

axios.get(`/products/${productId}`)

Using baseURL 'api' Axios formats the URL for subpages like so:

'http://app3.dev100.xyz/products/api/products/1'

Using baseURL 'https://app3.dev100.xyz/api' Axios formats the url for subpages correctly

'http://app3.dev100.xyz/api/products/1'
  • Related