【问题标题】:Send nested json data with get method using axios使用 axios 使用 get 方法发送嵌套的 json 数据
【发布时间】:2020-05-21 03:38:57
【问题描述】:

我正在尝试使用 axios 使用 get 方法发送嵌套的 json 数据,但问题是后端将子项视为字符串。

const TOKEN = "token"
const config = {
    headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        'Authorization': TOKEN,
    },
    data: {},
    params: {
        "page_id": 1,
        "filter": {
            "search": "name"
        }
    }
};
axios.get("http://localhost/api/pages", config)

如果我想在后端打印 filter 我会得到什么:

"{"search": "name"}"

【问题讨论】:

  • config.params.filter

标签: javascript json get nested axios


【解决方案1】:

您可能有两种选择:

1- 第一个选项是将收到的字符串解码为 json。

例如

---json_decode() 在 php 中

--- JSONObject() 在java中

--- JSON.parse() 在 nodejs 中

或任何其他方法,具体取决于您的后端语言...

2- 第二种选择是以这种格式发送您的对象:

params: {
    "page_id": 1,
    "filter[search]": "name"
}

注意不要把search放在引号里!

【讨论】:

    【解决方案2】:

    您可以在服务器端使用req.query

    function get(req, res, next) {
      const { filter } = req.query;
      console.log(filter);
      ...
    }
    

    【讨论】:

      【解决方案3】:

      做一个JSON.parse()Request.query.filter注意 Request 应该是后端的请求变量。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-11-29
        • 2017-06-23
        • 2011-07-28
        • 2019-07-25
        • 1970-01-01
        • 2013-05-04
        • 2012-06-12
        • 1970-01-01
        相关资源
        最近更新 更多