Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

112
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!