Retrieving the JSON Error Message Body from a Response when you set response type to arrayBuffer

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
    // Send a 500 http status code

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 => {
    if (permitId === -1) {
      setAlert(alert => [...alert, {id: 4, type: 'warning', message: 'Please select a permit number.'}])
    } else {
      if (month === '') {
        setAlert(alert => [...alert, {id: 5, type: 'warning', message: 'Please select a month.'}])
        // Generate Monthly Operating Report
      } else {
        // Generate Monthly Operating Report
        const monthDate = convertDateToMMDDYYYY(month)
        axios.get(`/generate/excel/report`, {
          headers: {
            Authorization: `Bearer ${token}`
          responseType: 'arraybuffer'
        }).then(res => {
          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([], {
            type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
          fileDownload(blob, fileName)
          setAlert(alerts => [...alerts, {id: 1, type: 'primary', message: 'Thank you for using We are powered by open source software.'}])
        }).catch(err => {
          setAlert(alerts => [...alerts, {id: 6, type: 'warning', message: }])
  } is of the type array buffer. Whenever I try to access 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.

Leave a Reply

Your email address will not be published.