The front-end request URL address carries Chinese parameters to the back-end for decoding.

The front-end request URL address carries Chinese parameters to the back-end for decoding.

I encountered a difficulty when making webscoket today. In order to display the user's nickname, I decided to use the method of carrying the user name in the request URL address. However, some users' names are in Chinese and even have strange characters. Send them to After the backend, after all the hard work of string cutting and replacement, we finally successfully got the user's parameter value, but it looked like this:

 socket = new WebSocket("ws://localhost:3090?id=许俊东?pass=123456")//前端代码
[ 'id', 'pass' ] [ '%E8%AE%B8%E4%BF%8A%E4%B8%9C', '123456' ]

In fact, they are Chinese parameters. During the get request process, they are automatically parsed by the browser and then become this format. Therefore, we need to re-decode the parameters. There are two solutions. The first one is seen online. Make some changes to the configuration file of the proxy server (such as modifying the default encoding of the tomcat connector, changing "iso8859-1" to "UTF-8"), but it seems that for some reasons, tomcat may not be used yet, and What to do, so here is the second method: change the backend code:

var a=req.url.replace('/?','').split('?')  //切割url地址获得字符串
    var key=[]
    var value=[]
    for(var i=0;i<a.length;i++)
    {
    
       
        var b=a[i].split('=')
        key.push(b[0])
        value.push(b[1])
    }
    console.log(key,value);
    const username=decodeURI(value[0])    //中文解码函数

There are more decoding functions here:
escape/unescape (the latter is the corresponding decoding function, similar below):
encode strings in hexadecimal, use %xx encoding for spaces, symbols and other characters, and use %xx encoding for Chinese and other characters %uxxxx encoding representation. Since JavaScript 1.5, this method has been deprecated.

encodeURI/decodeURI :
Encode the string in UTF-8 encoding. These characters: " ; , / ? : @ & = + $ " are not encoded.

encodeURIComponent/decodeURIComponent:
Encode all strings in UTF-8 encoding.

Guess you like

Origin blog.csdn.net/weixin_51295863/article/details/129268130