首页 > 解决方案 > 这个来自 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.' ]
  }
}

标签: phpnode.jsarraysjson

解决方案


您不需要使用 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/`,
};

推荐阅读