Quiero enviar una solicitud a una API y la información debe estar en el cuerpo y quiero usar una variable en eso. Pero cuando uso (size) o {size} o $ {size} no funciona. Cómo cargar una variable allí:
"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" });¿Por qué molestarse con el escape de comillas, la concatenación o la interpolación ( literales de plantilla ) cuando hay un método para encadenar una matriz y/u objeto?
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" });Estas son dos formas de hacerlo.
1.
"[\"variables\":{\"addToCartInput\":{\"productId\": " + SIZE + " ,\"clientMutationId\":\"addToCartMutation\"}}]" `["variables":{"addToCartInput":{"productId": ${SIZE},"clientMutationId":"addToCartMutation"}}]`Tenga en cuenta que el primero está usando comillas dobles. Mientras que el segundo está usando literales de plantilla.