繁体   English   中英

获取请求正文中的 JavaScript 变量

[英]JavaScript variable in the body of a fetch request

我想向 API 发送请求,信息必须在正文中,我想在其中使用一个变量。 但是当我使用(size){size}$ {size}它不起作用。 如何在那里加载变量:

"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"
});

当有一种方法可以对数组和/或 object 进行字符串化时,为什么还要使用引号 escaping、连接或插值( 模板文字)?

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"
});

获取有类似示例的文档

这是两种方法

1.

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

请注意,第一个使用双引号。 而第二个是使用模板文字。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM