【问题标题】:Nodejs encoding issueNodejs编码问题
【发布时间】:2015-06-12 00:20:47
【问题描述】:

我正在尝试从请求中获取数据,但格式或编码不是我想要的。

我尝试使用req.setEncoding('utf8')设置编码

我应该得到的字符串是: import Graphics.Element exposing (..) import Graphics.Collage exposing (..) import Color exposing (..) main : Element main = collage 500 500 [filled orange (circle (1 + 49)]

我实际得到的是:import+Graphics.Element+exposing+%28..%29%0D%0Aimport+Graphics.Collage+exposing+%28..%29%0D%0Aimport+Color+exposing+%28..%29%0D%0Amain+%3A+Element%0D%0Amain+%3D+collage+500+500+%5Bfilled+orange+%28circle+%281+%2B+49%29%5D

这是我读取数据并设置编码的地方:

function onPost () {
// When there is a POST request
app.post('/elmsim.html',function (req, res) {
    console.log('POST request received from elmsim')
    req.setEncoding('ascii')
    req.on('data', function (data) {
        // Create new directory
        createDir(data, res)
    })
})

}

任何帮助都会很棒!谢谢

【问题讨论】:

    标签: javascript node.js string encoding character-encoding


    【解决方案1】:

    你得到的字符串是一个 url 编码的字符串。

    您是否尝试在字符串上调用 decodeUriComponent?

    decodeURIComponent( string )
    

    【讨论】:

    • 我已经尝试过这样做。它返回的字符串接近正确。现在,所有空格都替换为“+”(加号)。由于输入中可能已经有一个加号,我如何区分什么是空格和什么是加号?
    • 理论上,url 编码确实将 url 替换为 %2B。你可以为此感到高兴! ;)
    • +500+%5Bfilled+orange+%28circle+%281+**%2B**+49%29%5D,注意你的encode中有+号,转换为%2B跨度>
    【解决方案2】:

    Luca 的回答是正确的,但 decodeURIComponent 不适用于包含加号的字符串。您必须使用 '%2B' 作为拆分器(这表示加号)拆分字符串,并将 decodeURIComponent 应用于每个单独的字符串。然后可以连接字符串,然后可以添加加号。

    这是我的解决方案:

    function decodeWithPlus(str) {
        // Create array seperated by +
        var splittedstr = str.split('%2B')
    
        // Decode each array element and add to output string seperated by '+'
        var outs = ''
        var first = true
        splittedstr.forEach(function (element) {
            if (first) {
                outs += replaceAll('+', ' ', decodeURIComponent(element))
                first = false
            }
            else {
                outs += '+' + replaceAll('+', ' ', decodeURIComponent(element))
            }
        })
        return outs
    }
    
    function replaceAll(find, replace, str) {
        var outs = ''
        for (i = 0; i < str.length; i++) {
            if (str[i] === find) {
                outs += replace
            }
            else {
                outs += str[i]
            }
        }
        return outs
    }
    

    【讨论】:

      猜你喜欢
      • 2022-01-17
      • 2011-04-13
      • 2017-11-10
      • 1970-01-01
      • 2011-03-15
      • 2012-05-20
      • 2011-09-13
      • 2011-02-03
      相关资源
      最近更新 更多