kyrolos magdy
kyrolos magdy

Reputation: 393

Circular JSON, when trying to stringify a JS object

we have this object, we need to get it as JSON instead of JS object, so we do it with JSON.stringify() and we receive this error:

Converting circular structure to JSON
>      --> starting at object with constructor 'ClientRequest'
>      |     property 'socket' -> object with constructor 'TLSSocket'
>      --- property '_httpMessage' closes the circle

and here is my whole end-point, I think it might have something to do with Axios, please note we uses TypeScript so actually this file is not .js file but .ts:

  app.post('/payment-key-request', async (req: any, res: any) => {
  const {auth_token, order_id} = req.body;
  const payload1 = {
    auth_token,
    amount_cents: 100,
    expiration: 3600,
    order_id,
    billing_data: {
      apartment: 803,
      email: "[email protected]",
      floor: 42,
      first_name: "Clifford",
      street: "Ethan Land",
      building: 8028,
      phone_number: 9135210487,
      shipping_method: "PKG",
      postal_code: 41523,
      city: "Jaskolskiburgh",
      country: "CR",
      last_name: "Nicolas",
      state: "Utah"
    },
    currency: "EGP",
    integration_id: 1 // something goes off here
  };


    let cache: any = [];
await Axios.post(
    "https://accept.paymobsolutions.com/api/acceptance/payment_keys",
    JSON.stringify(payload1),
    {
      headers: { "Content-Type": "application/json" }
    }
  )
    .then((resp: any) => {
      res.status(200).json({ ...resp });
    })
    .catch((error: any) => {
      if (error.response) {
        console.log("// Request made and server responded");
        console.log(error.response.data);
        console.log(error.response.status);
        console.log(error.response.headers);
      } else if (error.request) {
        console.log("// The request was made but no response was received");
        console.log(error.request);
      } else {
        console.log(
          "// Something happened in setting up the request that triggered an Error"
        );
        console.log(error.message);
      }
      res.status(400).json({ ...error });
    });

    cache = null;
})

Upvotes: 0

Views: 399

Answers (1)

Ry-
Ry-

Reputation: 224983

Instead of trying to respond with the entire response object, you should send just the parsed body:

res.status(200).json(resp.data);

Same with the error case:

res.status(400).json(error.response.data);

Upvotes: 1

Related Questions