Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

113
Vistas
JavaScript variable in the body of a fetch request

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"
});
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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

about 4 years ago · Juan Pablo Isaza Denunciar

0

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.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda