gonethen
V2EX  ›  问与答

前端小白求关于请求参数包含特殊符号(如"%")会报错的解决办法。

  •  
  •   gonethen · Mar 26, 2021 · 3195 views
    This topic created in 2052 days ago, the information mentioned may be changed or developed.

    关键字 vue/axios/element-ui

    团队遇到了传参报 400 的问题,初步断定是因为参数某个字段含有中文和"%"导致。因为不带"%"就不会报 400 错误。

    使用了 post 请求。

    11 replies  •  2021-03-26 15:08:30 +08:00
    Perry
    Perry
    Mar 26, 2021
    1
    encoding 做好了就不会有这问题
    ayase252
    ayase252
    Mar 26, 2021 via iPhone
    2
    urlencode
    ayase252
    ayase252
    Mar 26, 2021 via iPhone
    3
    我没审好题,我的锅。

    如果参数在 URL 上,确保传出去的时候 URLEncode 一遍,那边再 decode 。
    在 Body 中的应该不用,按约定来
    wenzichel
    wenzichel
    Mar 26, 2021
    4
    所有的参数均`encodeURIComponent`再传给后端接口!
    zhlssg
    zhlssg
    Mar 26, 2021
    5
    现在 get 请求如果有中文是会自己转换的吧
    gonethen
    gonethen
    OP
    Mar 26, 2021
    6
    @ayase252 #3 [![6j3478.png]( https://z3.ax1x.com/2021/03/26/6j3478.png)]( https://imgtu.com/i/6j3478)
    这样算是已经 urlencode 了吧?
    mhycy
    mhycy
    Mar 26, 2021
    7
    % 需要转义成 %25,你的请求里面出现了两个%
    gonethen
    gonethen
    OP
    Mar 26, 2021
    8
    @wenzichel #4 axios.post 接受的是一个对象,encodeURIComponent 却需要传递一个字符串,该怎么用呢? qs.stringify?
    eason1874
    eason1874
    Mar 26, 2021
    9
    encodeURI 和 encodeURIComponent 都会转义 % ,可以正常传入 "测试%和 9"

    你截图里显示没有转义,明显不是这两个其中一个的转义结果,应该是经过了其他处理,检查下吧。
    wenzichel
    wenzichel
    Mar 26, 2021
    10
    @gonethen #8 是的
    ysc3839
    ysc3839
    Mar 26, 2021
    11
    发代码看看吧,估计是你写的有问题。自己试了下,使用 axios 的 params 参数是不需要自己 encodeURI 的,会自动处理好。
    https://jsfiddle.net/w6e75ydu/
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1679 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 38ms · UTC 10:34 · PVG 18:34 · LAX 02:34 · JFK 05:34
    ♥ Do have faith in what you're doing.