Home > Net >  Angular can't reach image when in production mode URL not found
Angular can't reach image when in production mode URL not found

Time:09-28

I have an Angular app that uses an image in the nav bar like so: flag image

My problem is that whenever i enable production mode the site is not able to reach the image.

here is some context:

  • The image is located in a wwwroot folder: \wwwroot\Images\flags (the wwwroot is the default folder for c# web projects)
  • This is my environment.prod.ts:
export const environment = {
    production: true,
    apiUrl: '/api'
};
  • This is my environment.ts:
export const environment = {
    production: false,
    apiUrl: 'https://localhost:5569/api'
};
  • This is my lang.service.ts: from where i get the image:
getFlagUrl(fileName: string): string {
    const flag = fileName.split('-')[0];
    return `${environment.apiUrl.replace('api', '')}/Images/flags/${flag}.png`;
}

FYI

  • I use a back-end server with c# and i hit my API's with URL:PORTNAME/api
  • This is the error message when executing the app: image error code
  • In production mode i move my app into a local server with a different IP address than localhost. (I do not know the ip address, it should be dynamically gathered by the app itself no?)
  • if i use localhost/api in production mode i am able to see the flag in the local server but not from another computer, i am stuck at this lol)

Anyway i think it has something to do with the url in production?

CodePudding user response:

environment.apiUrl.replace('api', '') leads to:

  • https://localhost:5569//Images/flags/en.png for debug mode and to
  • //Images/flags/en.png in production.

Notice the double slash; while for the debug version, the browser fixes the error, in production an URL starting with a double slash is a valid URL that references another host, but uses the same protocol (http/https). See this answer for an explanation.

In order to make this work, you should get rid of the double dash, e.g. by using relative links

return `${environment.apiUrl}/../Images/flags/${flag}.png`;

or including the slash in the replace:

return `${environment.apiUrl.replace('/api', '')}/Images/flags/${flag}.png`;
  • Related