php - 这个来自 PHP 的 JSON 对象的 JS 等效项是什么?
问题描述
我正在尝试将此数据发布到 API 端点我无法弄清楚它需要实际通过的公式,我需要它与 NodeJS (axios) 一起使用来发布
$product = \Shoppy\Models\Product::create([
'title' => 'My test product',
'price' => 10,
'unlisted' => false,
'type' => 'service',
'currency' => 'EUR',
'stock_warning' => 0,
'quantity' => [
'min' => 1,
'max' => 10
],
'email' => [
'enabled' => false
]
]);
已编辑:根据@Nick的建议(在评论中):
let opts = {
method: "PUT",
headers: this.headers,
data: JSON.stringify({
"title": "My test product",
"price": 10,
"unlisted": false,
"type": "service",
"currency": "EUR",
"stock_warning": 0,
"quantity": {
"min": 1,
"max": 10
},
"email": {
"enabled": false
}
}),
url: `${this.base_url}/v1/products/`
};
let res = await axios(opts).catch(function(error) {
if (error.response) {
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
}
});
return res.data;
返回
{
message: 'The given data was invalid.',
errors: {
title: [ 'The title field is required.' ],
price: [ 'The price field is required.' ],
type: [ 'The type field is required.' ],
'email.enabled': [ 'The email.enabled field is required.' ],
currency: [ 'The currency field is required.' ]
}
}
解决方案
您不需要使用 JSON.stringify 包装数据对象。
const opts = {
method: 'PUT',
headers: this.headers,
data: {
title: 'My test product',
price: 10,
unlisted: false,
type: 'service',
currency: 'EUR',
stock_warning: 0,
quantity: {
'min': 1,
'max': 10,
},
email: {
'enabled': false,
},
},
url: `${this.base_url}/v1/products/`,
};
推荐阅读
- google-cloud-platform - 在 GCP 中创建自定义角色
- asterisk - 减少使用 goto 时的时间间隔
- php - 在具有多个值的字符串中搜索 Symfony 3
- react-native - 反应导航。在导航器顶部渲染额外的视图
- python - Python:绘制积分函数
- javascript - 如何将ajax响应数据附加到表td?
- matlab - 我如何计算这段代码中执行了多少个函数?
- ssis - SSIS:为什么我会看到“变量“的表达式评估失败。” 但是打包成功了吗?
- python - Python - 结合多处理和异步
- angular - 开玩笑 describe.each 或 test.each 不起作用