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
2 Answers
Reset to default 5Some 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),
})