为了账号安全,请及时绑定邮箱和手机立即绑定

带有空格的 Axios GET 请求参数

带有空格的 Axios GET 请求参数

白衣非少年 2021-11-12 17:13:39
目标我想使用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   }}这些参数foo, bar, encode, simple都可以工作并使用正确的数据生成响应。参数space, encoded不会生成正确的数据。请求以 200 成功,但不返回任何数据。我使用相同的查询在 Postman 中创建了相同的请求,以查看是否GET返回了预期的结果,并且确实如此。我%20在 Postman 中添加了它,它返回得很好。我+在 Postman 中添加了它,它也返回了预期的结果。题变量实现可能会出什么问题?如果没有像barparam这样的变量,我就无法做到这一点,因为该值正在传递给一个函数(Redux 操作)。对此的任何想法或想法都会有所帮助。如果需要更多信息,请发表评论。
查看完整描述

1 回答

?
有只小跳蛙

TA贡献1824条经验 获得超8个赞

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


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


在 URL 本身中定义您的查询参数

const whitespace = "white space";

axios.get(`/api?space=${whitespace}`);

自己编写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) => { /* ... */ } })


查看完整回答
反对 回复 2021-11-12
  • 1 回答
  • 0 关注
  • 660 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信