Question

I have frontend content that needs backend REST APIs to function. The APIs allow for cross-origin resource sharing (CORS). Typically we run the complete stack locally, including a user-mode Nginx instance tailored for development use which serves the frontend content. The full stack however is a bit too much to expect part time contractors to wrangle. So I'd like an approach very basic they can use to be effective and get stuff done.

Their current solution is horrible:

var port = location.port;
// base url of backend API
var url = window.location['origin'];
if (port != '443') {
    // assume we're running in "development" mode against a staging server
    url = "https://staging-server.somewhere.com";
}

Apart from the fact that this is furthering frontend content that is a bit kludgey as it is - it precludes the static content from being hosted in a variety of other ways, including a suite of functional and integration tests.

I have some ideas, like having them run a small web server that proxies to the backend APIs, but what I would really like is something simpler that allows me to default url in a less kludgey way. Ideally, there would be some manner of configuring url from a file ignored by version control (e.g., .gitignore).

Was it helpful?

Solution

I was able to create a solution that works for all manner of local development as well as production releases.

I created some JavaScript, apiurl.js, that sits alongside all of our other JavaScript content. If the apiurl.jsfile is present, I read its responseText into eval(). The frontend can therefore change the URL based on the content of that file.

E.g., apiurl.js has:

var apiurl = "https://staging-server.somewhere.com";

And the JavaScript to handle the content:

eval(responseText);
if (typeof(apiurl) != undefined) {
    url = apiurl;
}

The apiurl.js file is untracked by version control and not used in production.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top