简体   繁体   中英

How to converter utf8 at bodyparser in node.js

I live in South Korea

South Korea web ins't standardization for utf-8

Sometime I receive the "euc-kr" string

So It's occur error

when I used In express 3.x. It made the utf-8 automatically

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

but now I use express 4.x It do not that

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

So I don't know how to input the urlencoded 'utf-8' option

How to know input the utf-8 option in express 4.x?

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)
...

Generally it should be already utf-8 by default, but in this case try this:

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

Anyway if you want to parse JSON, and it seem so, 'utf-8' could not solve your problem becouse bodyParser doesn't work properly with this data format. For example if you try to use request.body to get your POST data you could find something like that

{ '{data1':'stringExample','data2':123}':''} or sometimes the annoyng undefined

Read a good explanation here enter link description here

Try to change this:

app.use(bodyParser.json());

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

With:

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();
       });
};

and use them when you need:

//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);

In this way you can catch just Json data as raw-data (as it was sent) without body-parser and then parse it with native json parser. Find more about that here and if you need to use GET url here Byee

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM