Link to home
Start Free TrialLog in
Avatar of itzik levy
itzik levyFlag for Israel

asked on

ReactJs/JavaScript fetch response returning undefined

I'm sending fetch request from ReactJS to nodeJS app which I developed (on http://local_server:8889/t.js),"local_server" is a Linux server in my organization running nodejs,

when I check in chrome developer i get:

  1. on console tab, "undefined" as seen in image 3.
  2. on header tab as seen in image 1.
  3. on the network tab, I get the desired response (this is what I want to see in my reactjs app when I press "Fetch Action Data" ).
     
    also, i add { mode: 'no-cors' } to the fetch because i got a cors error (if there is a better solution for production please recommend),

    if i replace the fetch URL to 'https://swapi.dev/api/films/' (a public rest endpoint on the web ) it works fine.

my ReactJs app looks like image 4.

my NodeJs app Ends with the lines in image 5.



import React, { useState, useEffect, useCallback } from 'react';
import './App.css';

function App() {
  const [datat, setDatat] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState(null);

  const fetchActionHandler = useCallback(async () => {
    setIsLoading(true);
    setError(null);
    try {
      
      //const response = await fetch('https://swapi.dev/api/films/'); //works fine
      const response = await fetch('http://local_server:8889/t.js',{ mode: 'no-cors' });  
      

      if (!response.ok) {
        console.log(response.Error);
        throw new Error('Something went wrong!');
     }
 
      const data = await response.text();
      
      
      setDatat(data);
      console.log(data);

    } catch (error) {
      console.log(error.message);
      setError(error.message);
    }
    setIsLoading(false);
  }, []);

  useEffect(() => {
    fetchActionHandler();
  }, [fetchActionHandler]);

 

  let content = <p>Found no Data.</p>;

  if (datat.length>0) {

    content =  datat;
  }

  if (error) {
    content = <p>{error}</p>;
  }

  if (isLoading) {
    content = <p>Loading...</p>;
  }

  return (
    <React.Fragment>
      <section>
        <button onClick={fetchActionHandler}>Fetch Action Data</button>
      </section>
      <section>{content}</section>
    </React.Fragment>
  );
}

export default App;

Open in new window


image 1

User generated image


image 2

User generated image


image 3User generated image


image 4

User generated image


image 5


User generated image

Avatar of ste5an
ste5an
Flag of Germany image

Without testing, shouldn't it be reponse.status in the status check? E.g.

import React, { useState, useEffect, useCallback } from 'react';
import './App.css';

function App() {
    const [datat, setDatat] = useState([]);
    const [isLoading, setIsLoading] = useState(false);
    const [error, setError] = useState(null);
    const fetchActionHandler = useCallback(async () => {
        setIsLoading(true);
        setError(null);
        fetch('http://local_server:8889/t.js', { mode: 'no-cors' })
            .then(response => {
                if (!response.ok) {
                    console.log(response.status);
                    throw new Error('Something went wrong!');
                }

                setDatat(response);
            })
            .catch(error => {
                console.error('Error:', error);
                setError(error.message);
            }).
            finally(() => {
                setIsLoading(false);
            });
    }, []);
/..}

export default App;

Open in new window

Avatar of itzik levy

ASKER

Hi,

Thanks for your answer ,
I run the above code and it gave me 0 in the console.log instead of undefined, everything else is the same

import React, { useState, useEffect, useCallback } from 'react';
import './App.css';

function App() {
  const [datat, setDatat] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState(null);

  const fetchActionHandler = useCallback(async () => {
    setIsLoading(true);
    setError(null);
//--

fetch('http://local_server:8889/t.js', { mode: 'no-cors' })
  .then(response => {
      if (!response.ok) {
          console.log(response.status);
          throw new Error('Something went wrong!');
      }

      setDatat(response);
  })
  .catch(error => {
      console.error('Error:', error);
      setError(error.message);
  })
  .finally(() => {
      setIsLoading(false);
  });
}, []);

//--
  useEffect(() => {
    fetchActionHandler();
  }, [fetchActionHandler]);

 

  let content = <p>Found no Data.</p>;

  if (datat.length>0) {

    content =  datat;
  }

  if (error) {
    content = <p>{error}</p>;
  }

  if (isLoading) {
    content = <p>Loading...</p>;
  }

  return (
    <React.Fragment>
      <section>
        <button onClick={fetchActionHandler}>Fetch Action Data</button>
      </section>
      <section>{content}</section>
    </React.Fragment>
  );
}

export default App;




Open in new window


Hey there,

Remember that fetch returns a promise, so you need to access the data via that promise (json() or text() depending on what you need). Accessing the data returns another promise, so you chain them together:

fetch('http://local_server:8889/t.js', { mode: 'no-cors' })
  .then(response => response.text())
  .then(data => {
    // deal with the data that the server sent back
    console.log(data)
    setDatat(response)
  })
  .catch(error => {
    // handle your failures here
      setError(error.message)
  })

Open in new window

Hi,

thanks for your answer,

but, "setDatat(response ) "  gave me

  Line 18:16:  'response' is not defined  no-undef

Open in new window

I changed it to "setDatat(data)" but still the same as in my firs code.

Ahh - sorry, typo on my part. What does the console show. Go with something simple first:

fetch('http://local_server:8889/t.js', { mode: 'no-cors' })
  .then(response => response.text())
  .then(data => console.log(data));

Open in new window

Run that and see what the console shows
Hi,
Thanks for your answer,
But it's the same problem console.log give me undefined

User generated image
I think the problem is maybe something in header because when I replace the URL to URL from the web it works fine.

const response = await fetch('https://swapi.dev/api/films/');const response = await fetch('https://swapi.dev/api/films/');
//this works fine, "https://swapi.dev/api/films/" is a public rest endpoint in the web  //this works fine, "https://swapi.dev/api/films/" is a public rest endpoint in the web  

const response = await fetch('http://local_server:8889/t.js',{ mode: 'no-cors' });  const response = await fetch('http://local_server:8889/t.js',{ mode: 'no-cors' });  
//"local_server" is a server in my organization running nodejs//"local_server" is a server in my organization running nodejs
 
 
but in the "local server" fetch i see the desired response in the chrome developer network response

User generated image
maybe something in the header
User generated image

Yeah - if you're still getting that error, then you're not using the code I showed you. The point of my code was to simplify the process so we can debug. If you're seeing the request complete in the Network tab, then you know you're getting data back.

Try my code as I showed and see what you get.
the first screenshot is with your code
It can't be - nothing in my code sent "Something went wrong" to the console, so that must be your code !!
Either use the network tab or Fiddler or WireShark to see what happens..
ASKER CERTIFIED SOLUTION
Avatar of itzik levy
itzik levy
Flag of Israel image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial