gonethen
V2EX  ›  问与答

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

  •  
  •   gonethen · Mar 26, 2021 · 2764 views
    This topic created in 1895 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
        1
    Perry  
       Mar 26, 2021
    encoding 做好了就不会有这问题
    ayase252
        2
    ayase252  
       Mar 26, 2021 via iPhone
    urlencode
    ayase252
        3
    ayase252  
       Mar 26, 2021 via iPhone
    我没审好题,我的锅。

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

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