Dan
Dan

Reputation: 1253

Setting window.location.href in react SPA production application yields unexpected results

I have a react 16.8.5 SPA hosted on an IIS 2016 back end on Windows Server 2016. In the app, the user can download a CSV report. To do this, the window.location.href is set to the URL of the web API that generates the report. For example:

window.location.href = 'api/generatereport'

The API returns a response with a text/csv content type. This works perfectly in our dev and test environments (the file is downloaded), but fails on the production environment. On the production environment, instead of returning CSV content from the API, HTML is returned that looks suspiciously like index.html. Note that I checked the IIS logs so I know the request never makes it that far. It seems to be a client issue. Also note that the production environment uses https - the others use http.

Any thoughts on what might vary in a production environment that would cause this request to be routed so incorrectly, and only in one environment? Mostly I was looking for a best guess or hunch.

Upvotes: 2

Views: 1964

Answers (2)

Dan
Dan

Reputation: 1253

This is a service worker issue. See removal of service-worker from reactjs app -nightmare for beginner...

Upvotes: 1

CJBS
CJBS

Reputation: 15695

When setting the location for the CSV file, try force-specifying the MIME type as part of the URL so that React doesn't assume it's trying to load another page within the React framework.

i.e.:

const target: string = window.location.origin + "/api/generatereport";
window.location.href = "data:text/csv;charset=utf-8," + target;

This will cause the CSV file to open as a separate window, and force the browser prompt to download the CSV stream as a file.

Note: there are file size limitations with this approach.

Upvotes: 0

Related Questions