1

I am working with node.js that runs on AWS lambda. As part of the logic there is an API call via axios GET/POST/DELETE API.

The code looks like:

const response = await axios.get(url); 
console.log(response);  // **returns [object Object]**

And in case of console.log(JSON.stringify(response, null, 2)); will crash.

Here is the response schema of axios: https://github.com/axios/axios#response-schema

And also the example of how to log the inner properties of the response:

axios.get('/user/12345')
  .then(function (response) {
    console.log(response.data);
    console.log(response.status);
    console.log(response.statusText);
    console.log(response.headers);
    console.log(response.config);
  });

I also read that the response object of the axios is a POJO here.

But didn't find any explanation how to convert it to Object that can be strigified as full response object.

Constantine Ch
  • 131
  • 3
  • 13
  • 1
    The response has circular dependencies. This link may help you: https://stackoverflow.com/questions/22333101/recursive-json-stringify-implementation – Raeisi Jun 07 '21 at 16:22
  • Try `console.log(JSON.stringify(response.data, null, 2));` instead. –  Jun 07 '21 at 16:23
  • @ChrisG it won't work in case of circular dependencies (The whole response needed not just its data). To show you can use `console.table(response)` too – Raeisi Jun 07 '21 at 16:50
  • @Mr But how is API data going to contain circular dependencies? If an API sends JSON, the data is serializable by definition. OP needing the entire object sounds weird to me; why exactly would they need that as stringifyied console output? –  Jun 07 '21 at 16:53
  • I was going to answer, but not sure if this will work for you: ```console.log(JSON.stringify({ ...response }, null, 2));``` should strip it to a base object. – Any Day Jun 07 '21 at 16:58
  • @ChrisG the whole of `response`, not just `response.data`. – Raeisi Jun 07 '21 at 17:06
  • @AnyDay It won't work because `{...response}` does not eliminate the circular dependencies. As I mentioned before this link has solved the problem. https://stackoverflow.com/questions/22333101/recursive-json-stringify-implementation – Raeisi Jun 07 '21 at 17:08
  • @Mr. Intriguing because that just creates a shallow copy of values, but I can't seem to reproduce the op's problem so I'm not sure honestly. – Any Day Jun 07 '21 at 17:14
  • @AnyDay spread operator does not make a deep copy, It just copies the root keys into another object. It's kind of molting (As you mentioned). The circular dependencies exist in interior objects. Of course, deep copy doesn't fix the problem either. We need to handle it by adding a function to verify met objects in converting process. – Raeisi Jun 07 '21 at 17:34

0 Answers0