【问题标题】:How to converter utf8 at bodyparser in node.js如何在 node.js 的 bodyparser 中转换 utf8
【发布时间】:2016-07-12 02:37:45
【问题描述】:

我住在韩国

韩国网络没有对 utf-8 进行标准化

有时我会收到“euc-kr”字符串

所以出现错误

当我使用 In express 3.x 时。它自动生成了 utf-8

app.use(express.static(__dirname));
app.use(connect.json());
app.use(connect.urlencoded('utf-8')); <-- this

但是现在我用的是 express 4.x 不是这样的

app.use(express.static(path.join(__dirname)));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

所以我不知道如何输入 urlencoded 'utf-8' 选项

如何知道在 express 4.x 中输入 utf-8 选项?

app-0 UnsupportedMediaTypeError: unsupported charset "EUC-KR"
app-0     at urlencodedParser (/home/node/Node/node_modules/body-parser/lib/types/urlencoded.js:102:12)
app-0     at Layer.handle [as handle_request] (/home/node/Node/node_modules/express/lib/router/layer.js:95:5)
...

【问题讨论】:

    标签: node.js express utf-8 body-parser


    【解决方案1】:

    通常默认情况下它应该已经是 utf-8,但在这种情况下试试这个:

    app.use(bodyParser.text({defaultCharset: 'utf-8'}));

    无论如何,如果您想解析 JSON,而且看起来如此,'utf-8' 无法解决您的问题,因为 bodyParser 无法正常使用这种数据格式。例如,如果您尝试使用 request.body 来获取您的 POST 数据,您可能会找到类似的东西

    { '{data1':'stringExample','data2':123}':''} 或者有时令人讨厌 未定义

    在这里阅读一个很好的解释enter link description here

    尝试改变这一点:

    app.use(bodyParser.json());

    app.use(bodyParser.urlencoded({extended: true }));

    与:

    var jsonParser = bodyParser.json();
    var urlencodedParser = bodyParser.urlencoded({ extended: false });
    
    var urlNotEncodedParser = function(req, res, next)
    {
      rawBody = '';
    
      req.on('data', function(chunk) {
           rawBody += chunk;
    
           if (rawBody.length > 1e6) requereqst.connection.destroy();
           });
    
      req.on('end', function() {
           req.rawBody = JSON.parse(rawBody);
           next();
           });
    };
    

    并在需要时使用它们:

    //without body-parser
    app.post('/json', urlNotEncodedParser, requestJsonCTRL);
    
    //with body-parser
    app.post('/notjson', urlencodedParser, requestCTRL);    
    
    //or catching all other request with routes
    app.use('/', urlencodedParser, routes);
    

    通过这种方式,您可以在没有 body-parser 的情况下仅捕获 Json 数据作为原始数据(发送时),然后使用本机 json 解析器对其进行解析。 查找更多关于 here 的信息,如果您需要使用 GET url here 再见

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-30
      • 2015-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-02
      • 2017-02-24
      • 2012-10-13
      相关资源
      最近更新 更多