如何将对象作为参数发送给后期处理请求

问题描述 投票:2回答:2

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

这是对象的外观。

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

我想使用访存,但我可以使用任何东西。

javascript reactjs fetch-api
2个回答
1
投票

一些流行的方法是

获取API

使用fetch()发布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);
    });

1
投票

来自MDN:Using Fecth

fetch('https://example.com/profile', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify(goodOrder),
})
© www.soinside.com 2019 - 2024. All rights reserved.