1

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.

Nimantha
  • 6,405
  • 6
  • 28
  • 69

1 Answers1

1

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);
  })
Will
  • 3,201
  • 1
  • 19
  • 17
  • Hi @Will ! oh sorry in the code i copied here i forgot result.json in the first "Then statement": / but i tried this and got the "same result", the difference is the request status is 200 but the body is still null(I think it changes to state 200 because the method is post) – FRANCISCO IGNACIO ALFARO Nov 23 '20 at 11:58
  • https://i.stack.imgur.com/ZhqWh.png (console.log(result) before result.json()) – FRANCISCO IGNACIO ALFARO Nov 23 '20 at 12:13
  • Looks like you have 2 problems. 1) The body is empty. The server must not be sending what you think it is sending. 2) the result is still `undefined`. I don't know where you put `result.json()` but your arrow functions in your `then` methods are missing return statements. An arrow function with a single expression will return that result. But you put logging in there and added curly braces. Those blocks need to explicitly return something for the next step in the chain. – Will Nov 23 '20 at 21:21
  • I upload a img here https://imgur.com/a/X0vTSEV this is returning body:null. – FRANCISCO IGNACIO ALFARO Nov 23 '20 at 21:33
  • Ok, that should solve the second problem. For the first problem, you can see the response in the console. The server isn't sending a the body. If you look at your code, you make a db request and get a response (hopefully). Then you initialize `lista` to an empty array. Then you map your db response, but don't store the results of the map, so it just gets thrown away. Then you send the empty `lista` array as the body. You probably want `let lista = resultSet.map(obj => {...` or something like that. Send the mapped resultSet, not an empty array. – Will Nov 24 '20 at 02:49
  • Idk man I solved the problem sending the request without headers...just method: POST – FRANCISCO IGNACIO ALFARO Nov 24 '20 at 23:44
  • Thank you for you time @Will – FRANCISCO IGNACIO ALFARO Nov 24 '20 at 23:44