在nodejs的post请求中设置charset

我想通过请求模块使用euc-kr字符集将表单数据发送到某个网站。 而且我也使用iconv-lite模块,因为nodejs支持的字符集不是很多。

无论如何,网站使用euc-kr字符集,所以我必须处理表单数据的编码(节点的默认字符集是utf-8)。 但是这样做效果不好,我试图改变一些选项,但是我现在一直呆着,所以你能告诉我一些提示。

 // added module request, iconv-lite(extendNodeEncoding) already. function postDocumentForm() { //Lets configure and request request({ url: 'http://finance.naver.com/item/board_act.nhn', //URL to hit headers: { 'Content-Type': 'content=text/html; charset=euc-kr' }, method: 'POST', encoding: 'euc-kr', form: { code:'000215', mode: 'write', temp: '', keyCount: '0', title: "폼 데이터 중 일부가 한글일 때", opinion: '0', body:'인코딩이 제대로 되지 않고 있음!' } }, function (error, response, body) { if (error) { console.log(error); } else { iconv.undoExtendNodeEncodings(); console.log(response.statusCode, response.body); } }); } 

这里是结果 ,奇怪的字符。

我试过了 :

 euc-kr to binary euc-kr to null euc-kr to utf-8 delete encoding option delete request header 

结果是??????@@?

最后,我得到了一个灵魂,我解决了这个问题。

如果您使用请求模块将数据作为表单发送,则模块将您的表单编码强制更改为utf-8。 所以,即使你设置你的表单编码到另一个字符集,模块再次将你的字符集更改为utf8。 你可以在1120-1130行的request.js上看到。

所以,你最好通过“body”选项发送数据,而不是“form”选项。 (作为查询string)

 body: "someKey=someValue&anotherKey=anotherValue...." 

注意它是如何处理接收身体编码的

 iconv = require('iconv-lite'); function postDocumentForm() { //Lets configure and request request({ url: 'http://finance.naver.com/item/board_act.nhn', //URL to hit headers: { 'Content-Type': 'content=text/html; charset=euc-kr' }, method: 'POST', encoding: null, form: { code:'000215', mode: 'write', temp: '', keyCount: '0', title: "폼 데이터 중 일부가 한글일 때", opinion: '0', body:'인코딩이 제대로 되지 않고 있음!' } }, function (error, response, body) { if (error) { console.log(error); } else { console.log(response.statusCode); var utf8String = iconv.decode(new Buffer(body), "ISO-8859-1"); console.log(utf8String); } }); }