Backend code: This is for a successful response. If the request gets through all the middle ware functions it will send an Excel file.
exports.generateMor = async(req, res) => {
try {
const wb = new xl.Workbook()
const ws = wb.addWorksheet('Sheet 1')
ws.cell(1, 1).string('String')
wb.write(fileName, res)
} catch(e) {
// Handle the error
foo()
// Send a 500 http status code
res.status(500).send()
}
}
This is the frontend code. The file is corrputed unless we change the response type to ‘arraybuffer’. If response type is ‘arraybuffer’ we can open the Excel File.
const formSubmitHandler = e => {
e.preventDefault()
if (permitId === -1) {
setAlert([])
setAlert(alert => [...alert, {id: 4, type: 'warning', message: 'Please select a permit number.'}])
} else {
if (month === '') {
setAlert([])
setAlert(alert => [...alert, {id: 5, type: 'warning', message: 'Please select a month.'}])
// Generate Monthly Operating Report
} else {
setAlert([])
// Generate Monthly Operating Report
const monthDate = convertDateToMMDDYYYY(month)
console.log(monthDate)
axios.get(`/generate/excel/report`, {
headers: {
Authorization: `Bearer ${token}`
},
responseType: 'arraybuffer'
}).then(res => {
setAlert([])
setAlert(alert => [...alert, {id: 1, type: 'primary', message: 'Generating Monthly Operating Report...'}])
const headerLine = res.headers['content-disposition']
const startFileNameIndex = headerLine.indexOf('"') + 1
const endFileNameIndex = headerLine.lastIndexOf('"')
const fileName = headerLine.substring(startFileNameIndex, endFileNameIndex)
const blob = new Blob([res.data], {
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
})
fileDownload(blob, fileName)
setAlert(alerts => [...alerts, {id: 1, type: 'primary', message: 'Thank you for using LiftStation.cloud. We are powered by open source software.'}])
}).catch(err => {
setAlert(alerts => [...alerts, {id: 6, type: 'warning', message: err.response.data.message }])
})
}
}
}
err.response.data is of the type array buffer. Whenever I try to access err.response.data.message it is undefined. However if I try to do this with type: arraybuffer commented out, I am able to.
I’m looking for a nonhacky solution to be able to download my xlsx file if the response is successful, or to display the error message if it is not able to be generated.