过滤查询参数无法通过avios从我的vue js应用程序获取?

时间:2020-07-14 07:53:12

标签: vue.js axios query-parameters

每当用户在文本字段中键入任何内容时,axios都会获取对url的请求 生成http://sandbox4.wootz.io:8080/api/data/1/action/?filter={id}like'%TE%',并应根据搜索(用户键入的内容)返回所有过滤的结果作为响应。但是目前,它没有给出已过滤的结果作为响应,而是给出了所有结果(未过滤的结果)。

注意:我已经通过发出一个get请求通过邮递员测试了上述URL,它完美地给出了过滤后的结果。为什么在我的应用程序代码中不会发生相同的事情?plz帮助

 getAsyncDataAction: debounce(function(name) {
      if (!name.length) {
        this.dataAction = [];
        return;
      }
      this.isFetching = true;
    
      api
        .getSearchData(this.sessionData.key,`/action/?filter={id}like'%${name}%'`)    
        .then(response => {
          this.dataAction = [];
                  response.forEach(item => {
            this.dataAction.push(item);
          });
          console.log('action results are'+JSON.stringify(this.dataAction)) //displays all the results(non-filtered)
        })
        .catch(error => {
          this.dataAction = [];
          throw error;
        })
        .finally(() => {
          this.isFetching = false;
        });
    }, 500), 

api.js

import axios from 'axios';
const props = {
  base_url: '/api/store',
  search_url: '/api/entity/search',
  cors_url: 'http://localhost',
  oper_url: '/api'
};

axios.defaults.headers.get['Access-Control-Allow-Origin'] = props.cors_url;
axios.defaults.headers.post['Access-Control-Allow-Origin'] = props.cors_url;
axios.defaults.headers.patch['Access-Control-Allow-Origin'] = props.cors_url;

async function getSearchData(key, path) {
  try {
    console.log('inside getSearchData path value is'+path)
    console.log('inside getSearchData and url for axios get is '+props.base_url + '/data' + path)

    let response = await axios({
      method: 'get',
      url: props.base_url + '/data' + path,
      headers: {'session_id': key}
    });

    if (response.status == 200) {
      console.log(response.status);
    }
    return response.data;
  } catch (err) {
    console.error(err);
  }
}

1 个答案:

答案 0 :(得分:1)

问题是您没有正确编码查询字符串。特别是,您的%标志必须变成%25

为此,我强烈建议使用Axios中的params选项。

例如

async function getSearchData(key, path, params) { // ? added "params"

  // snip

  let response = await axios({
    method: 'get',
    url: `${props.base_url}/data${path}`,
    params, // ? use "params" here
    headers: {'session_id': key}
  });

并使用

调用您的函数
const params = {}

// check for empty or blank "name"
if (name.trim().length > 0) {
  params.filter = `{id}like'%${name}%'`
}

api
  .getSearchData(this.sessionData.key, '/action/', params)

或者,手动编码查询参数

const filter = encodeURIComponent(`{id}like'%${name}%'`)
const path = `/action/?filter=${filter}`

应该产生类似的东西

/action/?filter=%7Bid%7Dlike'%25TE%25'