简体   繁体   中英

How to set POST encoding with request module on node.js?

I'm using request module on node.js but there is something problem with encoding option. beneath codes are simple post request, but I don't know how to set up encoding of form field data . I already set headers to 'Content-Type': 'application/x-www-form-urlencoded; charset=euc-kr' 'Content-Type': 'application/x-www-form-urlencoded; charset=euc-kr' But it doesn't works. field data is korean, like "안녕하세요", and I should post it with euc-kr encoding. (The site takes euc-kr, not utf8)

The same program on Java application, I coded like this :

PrintWriter wr = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "euc-kr"));

But I don't know how to in nodejs. Can anyone give some solution...?

Code Sample

//Load the request module
var request = require('request');

//Lets configure and request
request({
    url: 'http://google.com', //URL to hit
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=euc-kr' },
    method: 'POST',
    form: {
        field1: 'data',
        field2: 'data'
    }
}, function(error, response, body){
    if(error) {
        console.log(error);
    } else {
        console.log(response.statusCode, body);
    }
});

Finally I got a soultion, and I solved this problem.

If you send a data as a form using request module, the module change your form encoding to utf-8 by force. So even you setted your form encoding to another charset, the module changes your charset to utf8 again. You can see that at request.js on line 1120-1130.

So, You'd better send a data by 'body' option, not 'form' option.

Node doesn't support EUC-KR so you can use iconv-lite to extend the native encodings available and set the encoding option in request .

List of Natively Supported Encodings

iconv.extendNodeEncodings(); only works for node pre v4+. See here to get this working for a newer version of node.

var iconv = require('iconv-lite');
var request = require('request');

// This will add to the native encodings available.
iconv.extendNodeEncodings();

request({
  url: 'http://google.com', //URL to hit
  method: 'POST',
  form: {
    field1: 'data',
    field2: 'data'
  },
  encoding: 'EUC-KR'
}, function(error, response, body){
  if(error) {
    console.log(error);
  } else {
    console.log(response.statusCode, body);
  }
});

iconv.undoExtendNodeEncodings();

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