POV
POV

Reputation: 12015

How to change base url of backend in Angular?

I have path let path = "/";

When it call this path Angular makes path like:

http://localhost:4200/backend/api

But I need

http://localhost/backend/api

Without port, ho to set this option in Angular?

Upvotes: 2

Views: 9833

Answers (2)

Or Yaacov
Or Yaacov

Reputation: 3900

the best use is to set a base url in your enviromenmt.ts file. a nice article about enviorment files environment.ts file:

for example:

environment.ts file:

export const environment = {
    DefaultLanguage: "en",
    production: false,
    development: true,
    environmentName:"DEV",
    baseURL:"http://localhost/backend/api"    
};

environment.prod.ts:

export const environment = {
    DefaultLanguage: "en",
    production: true,
    development: false,
    environmentName:"PROD",
    baseURL:''
};

and then you can apply some logic as:

if (environment.development) {
    this.baseURL = environment.baseURL;
} else if(environment.baseUrl && environment.baseUrl != '') {
    this.baseURL = environment.baseUrl + "/api/";
} else {
    this.baseURL = location.origin + "/api/";
}

and make sure you have the following configuration on angular.json file:

"configurations": {
    "production": {
        "fileReplacements": [{
            "replace": "src/environments/environment.ts",
            "with": "src/environments/environment.prod.ts"
        }]
    }
}

This is the same for QA or UAT environments as well. See the picture below:

enter image description here

you can create multiple environments with different url hard-coded or logic based urls.

So let's reflect this change to package.json file:

enter image description here

Run npm run build:prod for:

`build:prod`: `ng build --configuration=production`

Run npm run build:dev for:

`build:dev`: `ng build --configuration=development`

Run npm run build:uat for:

`build:uat`: `ng build --configuration=uat`

Run npm run build:qa for:

`build:qa`: `ng build --configuration=qa`

Upvotes: 10

bLaXjack
bLaXjack

Reputation: 870

When you set your path as "/". It means scheme, host and port from your current window location. So if your window location is "http://localhost:4200/somePage", you will expect "http://localhost:4200" will be the baseURL. If you have made a reverse proxy of 80 to your backend. You should declare it as an independent, fully qualified url. For e.g.

const baseUrl = "http://localhost"

Upvotes: 1

Related Questions