【问题标题】:Axios GET Request Param with Whitespace带有空格的 Axios GET 请求参数
【发布时间】:2020-02-05 13:22:42
【问题描述】:

目标

我想使用 axios 为 GET 请求传递查询参数。参数值是字符串类型的变量,有空格。

问题

似乎axios 正在以我的后端无法理解的格式对参数进行编码。我对axios 编码进行了研究,发现axios 将空格编码为+ 而不是%20

示例

假设您有这个请求:

 const whitespace = "white space";
 const encodeWhitespace = encodeURI(whitespace);
 const noSpace = "no";

 axios.get('/api', {
   params: {
     'foo': 'bar',
     'bar': 'hello world',
     'space': whitespace,
     'encode': 'hello%20world', 
     'encoded': encodeWhitespace,
     'simple': noSpace
   }
}

参数foo, bar, encode, simple 全部工作并使用正确的数据生成响应。参数space, encoded 不会生成正确的数据。请求成功,返回 200,但没有返回任何数据。

我在 Postman 中使用相同的查询创建了相同的请求,以查看 GET 是否返回预期结果并且确实返回了预期结果。我在 Postman 中添加了%20,它返回就好了。我在 Postman 中添加了+,它也返回了预期的结果。

问题

变量实现可能出了什么问题?如果没有 bar 参数之类的变量,我将无法做到这一点,因为该值正在传递给函数(Redux 操作)。对此的任何想法或想法都会有所帮助。如果需要更多信息,请发表评论。

【问题讨论】:

标签: javascript react-redux axios


【解决方案1】:

好像这是 Axios 库的 an issue (or the default parameter serialization behavior)

所以要克服这个问题,你有两个选择。

  1. 在 URL 本身中定义查询参数
const whitespace = "white space";
axios.get(`/api?space=${whitespace}`);
  1. 编写您自己的paramsSerializer 来构建查询字符串。
const whitespace = "white space";
const encodeWhitespace = encodeURI(whitespace);
const noSpace = "no";

axios.get('/api', {
    params: {
        'foo': 'bar',
        'bar': 'hello world',
        'space': whitespace,
        'simple': noSpace
    },
    paramsSerializer: (params) => {
        // Sample implementation of query string building
        let result = '';
        Object.keys(params).forEach(key => {
            result += `${key}=${encodeURIComponent(params[key])}&`;
        });
        return result.substring(0, result.length - 1);
    }
});

注意:上面的paramsSerializer也可以在全局级别或Axios实例级别定义。

  • 全球层面
axios.defaults.paramsSerializer = (params) => { /* ... */ };
  • 实例级别
let axInstance = axios.create({ paramsSerializer: (params) => { /* ... */ } })

【讨论】:

  • 感谢您的回复。我之前尝试过第一种方法(我忘了把它放在我的问题中)但它不起作用。我在 axios 的 github 问题上看到了您的第二种方法,但该方法对我不起作用。 :( 不确定这里有什么好的替代方案。整个应用程序都使用 axios,所以这很糟糕。
  • 我测试了这两种方法,它们都通过用%20 替换空格正确地发送了查询参数。使用第二种方法时发送的查询字符串是什么?
  • Udith Gunaratna,您在答案中提供的参数序列化程序是否完整?我直接将它添加到源中,但它不起作用。
  • 注意:substr 已被弃用,最好使用substring,在这里阅读区别developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
  • @FayçalBorsali 谢谢,我更新了答案
猜你喜欢
  • 2020-11-04
  • 1970-01-01
  • 2021-02-12
  • 1970-01-01
  • 2021-04-19
  • 2020-05-11
  • 2023-04-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多