如何解决uni.request传值乱码的问题

如何解决uni.request传值乱码的问题

下面是我封装的代码

const BASE_URL = `http://localhost/app/`
export const myRequest = (options) => { //暴露一个function:myRequest,使用options接收页面传过来的参数
return new Promise((resolve)=>{//定义resolve用于外部接收
                uni.request({
                    url: BASE_URL + options.url,
                    data: options.data || {}, //接收请求的data,不传默认为空
                    method: options.method || 'GET', //接收请求的方式,如果不传默认为GET
                    header: {
                        'content-type': 'application/x-www-form-urlencoded;charset=UTF-8',
                    },
                    success: (res) => {
                        //console.log(res)        // 将请求结果resolve出去
                        resolve(res)        // 将请求结果resolve出去
                    }
                })
})

        }


下面是我调用的代码

this.myRequest({
                    url: '1.asp',
                    method:"POST",
                    data: {
                        id1: 4,
                        id2: 'addoil',
                        id3: this.eid,
                        s_l11_10: this.s_l11_10, //借用人姓名
                    },

                }).then(res => {

                    console.log(res)
                    if (res.data==true) {
                    uni.showToast({
                        title: "数据提交成功!",
                        duration: 2000, // 这个弹窗显示多少毫秒
                        
                    }),

这个s_l11_10里有中文的话发送过去,接收是乱码.
下面是输入和接受的截图,是我哪里编码不对吗?我也把charset=UTF-8改成charset=GB2312也还是乱码。

img

img

该回答引用ChatGPT
你的代码看起来没有对中文进行编码,导致传输时出现了乱码。可以尝试使用encodeURIComponent()对中文进行编码,修改一下你的代码如下:


const BASE_URL = `http://localhost/app/`
export const myRequest = (options) => {
    return new Promise((resolve)=>{
        uni.request({
            url: BASE_URL + options.url,
            data: options.data || {},
            method: options.method || 'GET',
            header: {
                'content-type': 'application/x-www-form-urlencoded;charset=UTF-8',
            },
            success: (res) => {
                resolve(res)
            }
        })
    })
}

// 对数据进行编码
const encodedData = Object.keys(options.data).map(key => {
    return encodeURIComponent(key) + '=' + encodeURIComponent(options.data[key]);
}).join('&');

// 调用时传入编码后的数据
this.myRequest({
    url: '1.asp',
    method:"POST",
    data: encodedData
}).then(res => {
    console.log(res)
    if (res.data==true) {
        uni.showToast({
            title: "数据提交成功!",
            duration: 2000, // 这个弹窗显示多少毫秒
        })
    }
})

这样就可以保证中文数据传输时不会出现乱码了。

不知道你这个问题是否已经解决, 如果还没有解决的话:

如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^