Thursday, 21 October 2021

HTTP Response with Content-Disposition doesn't trigger download

I use msw to mock backend responses for automated FE tests.

I wanted to create an Export Functionality for user-created data. I am POSTing a Request to the desired route, and want to return a response with a .csv ; .pdf ; .xls file which should be downloaded automatically.

I've been searching for appropriate ways to do that and came across the Content-Disposition Response Header.

Sadly the response doesn't trigger a save dialoge, nor start a download, but I can't find the mistake.

Let me show you the workflow:

some-component.vue

async submitExport() {
  const exportDataFilters = {
    docType: this.docType,
    startDate: this.startDate,
    endDate: this.endDate,
    selected: this.selected,
  };

  const response = await this.$store.dispatch('exportThings', exportDataFilters);
  console.log(response);
},

store-module.js

async exportThings(ctx, exportData) {
  const {
    docType, startDate, endDate, selected,
  } = exportData;

  return services.exportThingsForStuff(ctx.state.id, docType, startDate, endDate, selected);
},

services.js

export const exportThingsForStuff = async (thingsId, docType, startDate, endDate, pl) => axios.post(`/mock/things/${thingsId}/export`, pl, {
  headers: {
    'Content-type': docType,
  },
  params: {
    startDate,
    endDate,
  },

And Finally the MSW Response function from handlers.js

rest.post('/mock/things/thingId/export', (req, res, ctx) => {
  // Vars will be in use to mimic filter behavior, as soon as the download problem is solved
  const docType = req.headers.get('Content-type');
  const startDate = req.url.searchParams.get('startDate');
  const endDate = req.url.searchParams.get('endDate');
  const selected = req.body;


  
// Creating a test string and blobbing it.
const resDataString = 'testName,testLastName,\r\nJoe,Moe';
const blob = new Blob([resDataString], { type: 'text/csv' });

return res(
  ctx.status(200),
  ctx.set({
    'Content-Disposition': 'attachment; filename="things_export.csv"',
    'Content-Length': blob.size.toString(),
    'Content-Transfer-Encoding': 'binary',
    'Content-Type': 'text/csv',
  }),
  ctx.body(blob),
  ctx.delay(),
);

}),

I can't find the problem with it, since the response looks like expected:

Request URL: http://localhost:8080/mock/things/101/export?startDate=&endDate=
Request Method: POST
Status Code: 200 OK (from service worker)
Referrer Policy: strict-origin-when-cross-origin

RESPONSE HEADERS
content-disposition: attachment; filename="things_export.csv"
content-length: 37
content-transfer-encoding: binary
content-type: text/csv
x-powered-by: msw


from HTTP Response with Content-Disposition doesn't trigger download

No comments:

Post a Comment