I have ASP.NET Web API for server and ReactJS for client. My question is how to make the server to tell the client in which port the client should make requests. Now my server port is on 7082 and the connection is hardcoded like that:
const request = await requester(urls.accounts '/' accountId, methods.get);
and here is the url:
export const urls = {
accounts: 'https://localhost:7082/api/accounts',
};
everything is on "https: // localhost: 7082 / api", but this port "7082" is for my computer and is different for others. How to make when someone else downloads the application to be able to make requests on the server without changing the port manually.
CodePudding user response:
You should use custom environment variables in order to set the url properly for different environments.
For example, your localhost:7082 would be something you keep in your .env.local file for debugging purposes. Deployed out on a server you could have the same thing set to www.myapi.com in your .env.production file and it would be taken care of during build time.
export const urls = {
accounts: 'https://localhost:7082/api/accounts',
};
/*The above turns into the below */
export const urls = {
accounts: process.env.REACT_APP_API_URL,
};
Your .env.local file:
REACT_APP_API_URL=https://localhost:7082
Your .env.production file:
REACT_APP_API_URL=https://www.myapi.com
If you're asking about how you can have localhost:7082 on one computer and localhost:8072 on another computer functioning as the same site and can both be called from the same front-end, that would require code on your part to choose between the urls. Ideally, if you're running the api across multiple servers for any environment, they should all be set to the exact same url/port combination so a load balancer can handle it for you.