Axios TypeError: Converting circular structure to JSON

Advertisements

I have the following functions in a Node application:

Middleware

const recachePosts: any = async (req: Request, res: Response, next: NextFunction) => {
    try {
      const status = await cachePosts();
      ...
    } catch (err: any) {
      return res.status(422).json({
        status: false,
        message: err.message,
      });
    }
}

const cachePosts = async () => {
  const posts: any = await fetchAllPosts();
  ...
}

Service function:

const fetchAllPosts = async () => {
  console.log('Step 1');
  const posts: any = await axios.get(`https://url.com`);
  console.log('Step 2: ' + posts);
  // returns Step 2: [Object Object]
  console.log('Step 2: ' + JSON.stringify(posts));
  // returns TypeError: Converting circular structure to JSON
  return posts;
};

The line const posts: any = await axios.get(https://url.com); in the service function doesn’t seem to work. What am I doing wrong here?

>Solution :

load the post’s data or status variable, as posts is actually a axios response object

const fetchAllPosts = async () => {
  console.log('Step 1');
  const posts = await axios.get(`https://url.com`);
  
  // Log specific properties of the 'posts' object
  console.log('Step 2 - Data: ', posts.data);
  console.log('Step 2 - Status: ', posts.status);

  return posts;
};

Leave a ReplyCancel reply