Home > Blockchain >  Receiving undefined instead of JSON
Receiving undefined instead of JSON

Time:03-10

I am using React axios to receive the JSON (array of objects) from server (server side is written on Go, I checked via Postman, JSON is sent properly).

Here is how I get the data on client side:

export const getPostData = async () => {
    const URL = 'http://localhost:8083/test'
    try {
        const { data: { data }} = await axios.get(URL);
        console.log(data)
        return data;
    } catch (error) {
        console.log(error)
    }
};

And this is how the getPostData is called in App.js:

const App = () => {
  const [ posts, setPosts ] = useState([]);

  useEffect(() => {
    getPostData()
      .then((data) => {
        setPosts(data)
        console.log(data)
      })
  },[]);

The problem is I get undefined in browser console. I found many similar questions asked here, but I could not find the solution (the Access-Control-Allow-Origin header is set when I send the JSON).

What should I learn more, where could be the problem? I would be very grateful for any help!

If this could be helpful, here is how I send the JSON in Go:

    c.Header("Access-Control-Allow-Origin", "*")
    c.Header("Content-Type", "application/json")
    c.JSON(http.StatusOK, gin.H{
        "message": "Hello",
    })

CodePudding user response:

This looks suspect:

const { data: { data }} = await axios.get(URL);

That tries to read a property called data from an object on the data property of the response from axios, like this without the destructuring:

const data = (await axios.get(URL)).data.data;

Your Go code doesn't look like it puts a {"data": ___} wrapper around what it sends, and Axios only adds one layer of {data: ___} wrapper to what it gives you in the response, not two.

If you want the object from the JSON response, remove the inner destructuring:

const { data } = await axios.get(URL);

data will be {message: "Hello"} assuming the Go code sends the JSON {"message": "Hello"}.


Separately, your JavaScript code seems to expect an array of posts, but your Go code is just sending {"message": "Hello"}.

  • Related