JavaScript-ReactJS problem with GET fetch request ReactJS

127 Views Asked by At

I'm trying to doing a basic GET request from ReactJS app to a Node.js API, but I'm getting a response with status 304. I need get a 200 status to save the response of GET in a variable. (Im running Reactjs app in port 3000 and Nodejs API in port 3300)

Node API:

app.get('/serviciosextras', async (req, res) => {
let connection;
console.log(('Servicios Extras'));

try {
    connection = await oracledb.getConnection({
        user: 'portafolio',
        password: '123',
        connectString: "localhost:1521/orcl"
    });

    const result = await connection.execute(
        `SELECT  dep.id_departamento,
                 se.id_servicio,
                 se.precio_servicio            
         FROM departamento_servicio_detalle dsd
         JOIN departamento DEP ON (dsd.id_departamento = dep.id_departamento)
         JOIN servicio_extra SE ON (dsd.id_servicio = se.id_servicio)
         ORDER BY 1 ASC`
    )

    const resultSet = result.rows;

    let lista = [];

    resultSet.map(obj => {
        let serviciosSchema = {
            'id_departamento': obj[0],
            'id_servicio': obj[1],
            'precio_servicio': obj[2]
        }
        lista.push(serviciosSchema);
    });

    console.log(lista);

    res.json(lista);

    connection.close();
} catch (err) {
    console.error(err);
}
});

GET request from Reactjs

const getExtraServices = () => {
let endpoint = `${URL}serviciosextras`;

const requestOptions = {
  method: "GET",
  mode: 'no-cors'
  // headers: {
  //   "Content-Type": "application/json",
  //   Accept: "application/json"
  // },
};
console.log(endpoint);

fetch(endpoint, requestOptions)
  .then((res, err) => {
    console.log(res);
  })
  .then(result => {
    console.log('fue aqui');
    console.log(result);
  })
  .catch(err => {
    console.log('ERROR');
    console.log(err);
  })
}

Im calling the method from this button:(onClick={getExtraServices()})

<Fab onClick={(e) => {
              e.preventDefault();
              getExtraServices();
            }} variant="extended">
              <NavigationIcon style={{marginRight: 'theme.spacing(1)'}} />
                Navigate
            </Fab>

so... I'm getting this: Firefox Console when I clicked button to call getExtraServices() res is undefined

Network console of GET request I got a response but the status is 304, so I can't get this from code. :/

Console of Nodejs API this console.log if from console.log(lista) before send the res.json(lista)

Does someone know how can I fix this? I need get the response of the GET request to charge a list in ReactJS app, but I can't because the response has body:null.

1

There are 1 best solutions below

7
On

Error 304 isn't the problem.

It looks like you are missing a statement to turn your response into JSON.

Here's an example from MDN:

fetch('https://example.com/profile', {
  method: 'POST', // or 'PUT'
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify(data),
})
.then(response => response.json())
.then(data => {
  console.log('Success:', data);
})
.catch((error) => {
  console.error('Error:', error);
});

In particular:

.then(response => response.json())

In your code:

fetch(endpoint, requestOptions)
  .then((res, err) => {
    console.log(res); // logging res
    // no data being returned here
  })
  .then(result => {
    console.log('fue aqui');
    console.log(result); // therefore result is undefined
  })
  .catch(err => {
    console.log('ERROR');
    console.log(err);
  })