【问题标题】:How to send pass an object as a parameter to a post request如何将对象作为参数发送到发布请求
【发布时间】:2020-04-25 12:25:04
【问题描述】:

我正在尝试将对象作为参数传递给发布请求,但我完全不知道该怎么做。

这就是对象的样子。

const goodOrder = {
    order: {
      cupcakes: [
        {
          base: "vanillaBase",
          toppings: ["sprinkles"],
          frosting: "vanillaFrosting"
        },
        {
          base: "redVelvetBase",
          toppings: ["gummyBears"],
          frosting: "redVelvetFrosting"
        }
      ],
      delivery_date: "Sat, 15 Sep 2018 21:25:43 GMT"
    }
  };

我想使用 fetch 但我可以使用任何东西。

【问题讨论】:

  • 参数是什么意思?是否意味着作为查询参数?作为表单体?作为 JSON 体?您的 api 具体期望是什么?因为如果它应该作为 JSON 字符串放入查询参数中,那么下面将其放入正文的答案可能根本行不通。

标签: javascript reactjs fetch-api


【解决方案1】:

来自 MDN:Using Fecth

fetch('https://example.com/profile', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify(goodOrder),
})

【讨论】:

    【解决方案2】:

    一些流行的方法是

    获取 API

    使用fetch() POST JSON 编码的数据。

    fetch('https://example.com/order', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(goodOrder),
        })
        .then((response) => response.json())
        .then((goodOrder) => {
            console.log('Success:', goodOrder);
        })
        .catch((error) => {
            console.error('Error:', error);
        });
    

    Axios

    Axios 是一个用于发出 HTTP 请求的开源库,因此您需要将它包含在您的项目中。您可以使用 npm 安装它,也可以使用 CDN 包含它。

    axios({
        method: 'post',
        url: 'https://example.com/order',
        data: goodOrder
    })
        .then((response) => {
            console.log(response);
        }, (error) => {
            console.log(error);
        });
    

    【讨论】:

      猜你喜欢
      • 2016-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-28
      • 1970-01-01
      • 2015-09-18
      • 1970-01-01
      相关资源
      最近更新 更多