Search code examples
javascriptfetch

How to add nested object to fetch POST body?


Given a simple fetch request i.e.

   fetch('https://api.com/endpoint', {
      method: "POST"
    });

Is it possible / how can following object be converted to query params / query string to append to the fetch request? Most methods online recommend using new URLSearchParams helper, however it doesn't seem to work with nested objects and when converted to string these nested objects are returned as [Object object] string. Ideal solution should not rely on any third party packages.

  {
    side: 'buy',
    symbol: 'AAPL',
    type: 'market',
    qty: '2',
    time_in_force: 'gtc',
    order_class: 'bracket',
    take_profit: {
      limit_price: '200'
    },
    stop_loss: {
      stop_price: '200'
    }
  }

Solution

  • Form your fetch request like this:

    
     fetch('https://api.com/endpoint', {
          method: "POST",
          headers: {
          'Content-Type': 'application/json'
              },
         body: JSON.stringify(dataYouWannaPost)
    
        });