带有空格的 Axios GET 请求参数

Ben*_*ves 8 javascript react-redux axios

目标

我想使用axios. 参数值是一个字符串类型的变量并且有空格。

问题

似乎axios是以我的后端不理解的格式对参数进行编码。我已经对axios编码进行了研究,它似乎axios将空格编码为 a+而不是%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
   }
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

小智 7

似乎这是Axios 库的一个问题(或默认参数序列化行为)

因此,要克服这一点,您有 2 个选择。

  1. 在 URL 本身中定义您的查询参数
const whitespace = "white space";
axios.get(`/api?space=${whitespace}`);
Run Code Online (Sandbox Code Playgroud)
  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);
    }
});
Run Code Online (Sandbox Code Playgroud)

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

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