如何将对象作为参数发送给 post 请求
How to send pass an object as a parameter to a post request
我正在尝试将对象作为参数传递给 post 请求,但我完全不知道该怎么做。
这就是对象的样子。
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,但我可以使用任何东西。
来自 MDN:Using Fecth:
fetch('https://example.com/profile', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(goodOrder),
})
一些流行的方法是
获取API
使用fetch()
到POSTJSON编码的数据。
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);
});
我正在尝试将对象作为参数传递给 post 请求,但我完全不知道该怎么做。
这就是对象的样子。
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,但我可以使用任何东西。
来自 MDN:Using Fecth:
fetch('https://example.com/profile', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(goodOrder),
})
一些流行的方法是
获取API
使用fetch()
到POSTJSON编码的数据。
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);
});