简体   繁体   English

如何实现这样的 axios API 查询参数?

[英]How do I implement the axios API query params like this?

This is the first time I found an API like this, the form in the params key is like an array but maybe it's not an array and how is it implemented in axios?这是我第一次发现这样的API,params键中的形式就像一个数组但可能不是数组,它是如何在axios中实现的?

{baseUrl}/list?filter[v3_p.name]=Package Data&filter[pro.name]=Indosat&filter[pp.category]=Voucher&filter[pd.is_enable]=1 {baseUrl}/list?filter[v3_p.name]=Package Data&filter[pro.name]=Indosat&filter[pp.category]=Voucher&filter[pd.is_enable]=1

My code in axios like this:我在 axios 中的代码如下:

export const filterProduk = (data) => async (dispatch) => {
  try {
    const params = { filter: data }
    const res = await axios.get(`${baseUrl}/list`, data, {
      params,
      paramsSerializer: function paramsSerializer(params) {
        return Object.entries(Object.assign({}, params, { filter: 'HIDDEN' })).map(([key, value]) => `${key}=${value}`).join('&')
      }
    });
    dispatch({
      type: FILTER_SUCCESS,
      payload: res.data.data
    });
  } catch (error) {
    dispatch({
      type: FILTER_FAILED,
      payload: error.response.data,
    });
  }
};

and I have tried as well我也试过了

export const filterProduk = (data) => async (dispatch) => {
  try {
    const res = await axios.get(`${baseUrl}/list`, data, {
      params: {
        filter: [data.package, data.provider, data.category, data.is_enable]
      }
    });
    dispatch({
      type: FILTER_SUCCESS,
      payload: res.data.data
    });
  } catch (error) {
    dispatch({
      type: FILTER_FAILED,
      payload: error.response.data,
    });
  }
};

I don't get it in any documentation, and hope to get an answer here!我没有在任何文档中得到它,并希望在这里得到答案! Thankyou谢谢

You can use qs.stringify to serialize the params.您可以使用qs.stringify序列化参数。 And you should pass the config object as the second argument to axios.get .您应该将config object 作为第二个参数传递给axios.get

axios.get(`${baseUrl}/list`, {
  params,
  paramsSerializer: (params) => qs.stringify(params, { encode: false }),
})

A suggestion: You could set up the API base URL using axios.defaults.baseURL or create a custom axios instance and configure it to avoid having to type it in every call. A suggestion: You could set up the API base URL using axios.defaults.baseURL or create a custom axios instance and configure it to avoid having to type it in every call.

// axios.js

import axios from 'axios'

export default axios.create({
  baseURL: 'https://api.example.com'
})

// queries.js

import axios from './axios'

axios.get('/list', {
  params,
  paramsSerializer: (params) => qs.stringify(params, { encode: false }),
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM