带空格的Axios GET请求参数

时间:2019-10-08 09:05:46

标签: javascript react-redux axios

目标

我想使用axios传递GET请求的查询参数。 param值是string类型的变量,具有空格。

问题

似乎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是否返回了预期的结果,并且确实如此。我在邮递员中添加了%20,它返回的效果很好。我在Postman中添加了+,它也返回了预期的结果。

问题

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

1 个答案:

答案 0 :(得分:0)

似乎是Axios库的an issue (or the default parameter serialization behavior)

因此,要解决此问题,您有2个选择。

  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.substr(0, result.length - 1);
    }
});
  

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

  • 全球水平
axios.defaults.paramsSerializer = (params) => { /* ... */ };
  • 实例级别
let axInstance = axios.create({ paramsSerializer: (params) => { /* ... */ } })
相关问题