Home > Net >  res.send() creates TypeError: Converting circular structure to JSON
res.send() creates TypeError: Converting circular structure to JSON

Time:12-02

I know this error message has been asked before, but I don't believe other solutions work for me.

I'm trying to build a backend express server to handle API calls for a React app. I wrote a getData() function to do this, used by an app.post() to send it to the front-end.

The error only pops up when using res.send(), e.g. my API calls work, just break when sending.

Here's the relevant code:

const getData = async route => {
    const config = {
        headers: {
            'Authorization': `Bearer ${TOKEN}`,
            'Content-Type': 'application/json;charset=utf-8'
        }
    }

    let corrRoute = route[0] == '/' ? route : '/'   route
    return await axios(`${URL}${corrRoute}?api_key=${API_KEY}`, config)
}


app.post('/api', async (req, res) => {
    let { route } = req.body
    res.send(await getData(route))
})

If I replace the res.send at the end there with console.log it prints out perfectly fine. The error is being produced in the server's index.js file, not in the React app.

Here is the full error text:

[server] (node:9680) UnhandledPromiseRejectionWarning: TypeError: Converting circular structure to JSON
[server]     --> starting at object with constructor 'ClientRequest'    
[server]     |     property 'socket' -> object with constructor 'TLSSocket'
[server]     --- property '_httpMessage' closes the circle
[server]     at JSON.stringify (<anonymous>)

CodePudding user response:

Axios returns a lot more than just the data you want. It returns a response object, warts and all, which will get interpreted as such. And you're sending that response object. It would be the same as res.send(res) (except for it being a different response object).

In order to get the actual data from Axios you'll need to change the following line:

return await axios(`${URL}${corrRoute}?api_key=${API_KEY}`, config)

to

const data = await axios(`${URL}${corrRoute}?api_key=${API_KEY}`, config);
return data.data;
  • Related