0

I are trying to send 'covidEvent' and 'location' to the backend but am getting an annoying error of 'Cannot set headers after they are sent to the client' Below is a component that creates input boxes that has SQL parameters tied to them. Selecting the 3 variables triggers an SQL query on the back end.

import React from 'react'
import Header from './Header'
import CovidData from './CovidData'

function Covid() {
  const [locations, setLocations] = React.useState(null)
  const [covidEvent, setCovidEvent] = React.useState('')
  const [timePeriod, setTimePeriod] = React.useState('')
  const [location, setLocation] = React.useState('')

  React.useEffect(() => {
    fetch('/Locations')
      .then((res) => res.json())
      .then((locations) => setLocations(locations))
  }, [])

  function handleCovidEventChange(event) {
    setCovidEvent(event.target.value)
  }

  function handleTimePeriodChange(event) {
    setTimePeriod(event.target.value)
  }

  function handleLocationChange(event) {
    setLocation(event.target.value)
  }

  return (
    <div id='body'>
      <Header />
      <a href='/'>Home</a>
      <div className='columns'>
        <div className='cols'>
          <select value={covidEvent} onChange={handleCovidEventChange}>
            <option>Cases</option>
            <option>Deaths</option>
            <option>Vaccinations</option>
          </select>
        </div>
        <div className='cols'>
          <select value={timePeriod} onChange={handleTimePeriodChange}>
            <option>Per Day</option>
            <option>Per Month</option>
            <option>Per Year</option>
          </select>
        </div>
        <div className='cols'>
          <select value={location} onChange={handleLocationChange}>
            {!locations ? (
              <option>Fetching Locations...</option>
            ) : (
              locations.map((x, y) => <option key={y}>{x}</option>)
            )}
          </select>
        </div>
      </div>

      {location ? (
        <CovidData
///////// This is where the problem seems to be - sending this to the back end and having    ///////// the backend use it throws error 'Cannot set headers after they are sent to the ///////// client'
          covidEvent={covidEvent}
          timePeriod={timePeriod}
          location={location}
        />
      ) : (
        'Waiting for Selection...'
      )}
    </div>
  )
}

export default Covid

Additionally, here is the function that is receiving the above parameters in the backend. I put ad-hoc variables in the SQL query to make sure it works by itself, and it does.

async function selectCovidEventsPerMonth(req, res) {
  let connection
  try {
    connection = await oracledb.getConnection(config)

    console.log('connected to database')
    **//Uncommenting this leads to an error on trying to use these parameters.**
    //console.log(covidEvent)
    //console.log(location)
    result = await connection.execute(
      `SELECT   
        COUNTRY, 
        SUM(TOTALCASES), 
        EXTRACT(YEAR FROM EVENTDATE), 
        EXTRACT(MONTH FROM  EVENTDATE) 
      FROM 
        COVIDEVENT WHERE COUNTRY = 'Afghanistan'
      GROUP BY 
        EXTRACT(MONTH FROM EVENTDATE), 
        EXTRACT(YEAR FROM EVENTDATE), 
        COUNTRY
      ORDER BY 
        EXTRACT(YEAR FROM EVENTDATE), 
        EXTRACT(MONTH FROM EVENTDATE)`
    )
  } catch (err) {
    return res.send(err.message)
  } finally {
    if (connection) {
      try {
        await connection.close()
        console.log('close connection success')
      } catch (err) {
        console.error(err.message)
      }
    }
    if (result.rows.length == 0) {
      return res.send('query send no rows')
    } else {
      return res.send(result.rows)
    }
  }
}

app.get('/CovidEventsPerMonth', function (req, res) {
  selectCovidEventsPerMonth(req, res)
})

I tried using axios to send the request but that did not change any error. I also used Postman to test the API with the parameters in the URL but it still showed the two variables as undefined.

SankaF498
  • 1
  • 1
  • I guess you try to send your query to a PHP backend. Something like this error can occur, if, for example, you have 2 `` tags in one file. – Flo Ragossnig Mar 29 '22 at 21:39
  • The backend is in express.js. – SankaF498 Mar 29 '22 at 21:51
  • 1
    Ah sorry, I think this. Has already been answered https://stackoverflow.com/questions/7042340/error-cant-set-headers-after-they-are-sent-to-the-client – Flo Ragossnig Mar 29 '22 at 22:07
  • Check if your code goes into the `catch` with values sent from front-end. If it does, then response is being sent twice. First in catch as `return res.send(err.message)` and second after resolving condition `if (result.rows.length == 0)`. Make sure `res.send()` is executed only **once** – Batman Mar 29 '22 at 22:32

0 Answers0