Home > Software engineering >  JavaScript variable in the body of a fetch request
JavaScript variable in the body of a fetch request

Time:12-06

I want to send a request to an API and the info has to be in the body and I want to use one variable in that. But when I use (size) or {size} or $ {size} it doesn't work. How to load a variable there:

"body": "[\"variables\":{\"addToCartInput\":{\"productId\":\ ** SIZE ** \,\"clientMutationId\":\"addToCartMutation\"}}]",

var SIZE = "NI115N001-A130045000";
fetch("https://www.zalando.pl/api/graphql/add-to-cart/", {
  "headers": {
    "accept": "*/*",
    "accept-language": "pl-PL,pl;q=0.9",
    "content-type": "application/json",
    "x-zalando-feature": "pdp",
  },
  "referrerPolicy": "strict-origin-when-cross-origin",
  "body": "[\"variables\":{\"addToCartInput\":{\"productId\":\ ** SIZE ** \,\"clientMutationId\":\"addToCartMutation\"}}]",
  "method": "POST"
});

CodePudding user response:

Why bother with quotes escaping, concatenation or interpolation (Template litterals) when there is a method to stringify an array and/or object?

var SIZE = "NI115N001-A130045000";

// Prepare the data
var data_to_send = [
  variables:{
    addToCartInput:{
      productId: SIZE,  // The variable is used here
      clientMutationId: "addToCartMutation" // Assuming that is a string
    }
  }
];

// Stringify the data
var data_stringified = JSON.stringify(data_to_send);

fetch("https://www.zalando.pl/api/graphql/add-to-cart/", {
  "headers": {
    "accept": "*/*",
    "accept-language": "pl-PL,pl;q=0.9",
    "content-type": "application/json",
    "x-zalando-feature": "pdp",
  },
  "referrerPolicy": "strict-origin-when-cross-origin",
  "body": data_stringified, // Use the stringified data here
  "method": "POST"
});

Fetch Documentation where there is a similar example

CodePudding user response:

These are two ways to do that

1.

"[\"variables\":{\"addToCartInput\":{\"productId\": "   SIZE   " ,\"clientMutationId\":\"addToCartMutation\"}}]"
`["variables":{"addToCartInput":{"productId": ${SIZE},"clientMutationId":"addToCartMutation"}}]`

Please note that first one is using double quotes. While second one is using template literals.

  • Related