最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to send pass an object as a parameter to a post request - Stack Overflow

programmeradmin0浏览0评论

I'm trying to pass an object as a parameter to a post request and I am totally lost on how to do it.

This is what the object looks like.

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

I'd like to use fetch but I can use anything.

I'm trying to pass an object as a parameter to a post request and I am totally lost on how to do it.

This is what the object looks like.

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

I'd like to use fetch but I can use anything.

Share edited Jan 8, 2020 at 1:12 Ismael Padilla 5,5865 gold badges25 silver badges37 bronze badges asked Jan 8, 2020 at 0:15 Cory AllenCory Allen 1592 silver badges12 bronze badges 1
  • What do you mean by parameter? Do mean as a query parameter? As a form body? As a JSON body? What is your api expecting specifically? Because if it’s supposed to be put into a query param as a JSON string, the answers below will that are putting it into the body simply may not work. – Alexander Staroselsky Commented Jan 8, 2020 at 1:12
Add a ment  | 

2 Answers 2

Reset to default 5

Some popular methods are

Fetch API

Use fetch() to POST JSON-encoded data.

fetch('https://example./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 is an open source library for making HTTP requests so you need to include it in your project. You can install it using npm or you can include it using a CDN.

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

From MDN: Using Fecth:

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

评论列表(0)

  1. 暂无评论