简体   繁体   English

获取请求正文中的 JavaScript 变量

[英]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.我想向 API 发送请求,信息必须在正文中,我想在其中使用一个变量。 But when I use (size) or {size} or $ {size} it doesn't work.但是当我使用(size){size}$ {size}它不起作用。 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"
});

Why bother with quotes escaping, concatenation or interpolation ( Template litterals ) when there is a method to stringify an array and/or object?当有一种方法可以对数组和/或 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"
});

Fetch Documentation where there is a similar example 获取有类似示例的文档

These are two ways to do that这是两种方法

1. 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.而第二个是使用模板文字。

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

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