Search code examples
jsonstripe-paymentsstringify

JSON stringify not producing expected json


This is a question for anyone who has used Stripe.js. I am trying to build a payment system with express and node. I have been stuck on this problem for about a day. I just want to post a json object with {"token":"token_val","item":"item_val"}. I am so close to getting it done, but when I post the data to my payment route my json object is messed up. I am getting a json of the form {'{"token":"token_val","item":"item_val"}': ''}.

var stripeHandler = StripeCheckout.configure({
    key: stripePublicKey,
    locale: 'en',
    token: function(token){
        var cartItem = document.getElementById("Monthly").id;
        var data = [{stripeTokenId: token.id, items: cartItem}];
        fetch('/purchase', {
          method: "POST", // *GET, POST, PUT, DELETE, etc.
          mode: "cors", // no-cors, cors, *same-origin
          cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
          credentials: "same-origin", // include, *same-origin, omit
          headers: {
            // "Content-Type": "application/json",
            "Content-Type": "application/x-www-form-urlencoded",
          },
          redirect: "follow", // manual, *follow, error
          referrer: "no-referrer", // no-referrer, *client
          body: JSON.stringify(data) // body data type must match "Content-Type" header
        })
    }
  })

Is there something wrong with this post that's causing the issue? I can't seem to understand why I'm getting this json obj key with a blank value. I have tried two different content types, but nothing really seems to make a difference.


Solution

  • The problem was that I was not using express.json(). I added app.use(express.json()) to my app.js file and this fixed everything. I hope this helps someone.