var http = require('http');
var querystring = require('querystring');
// 请求json数据
var postData = {
name:'awu'
};
// 请求数据字符串化
postData = querystring.stringify(postData);
var opt = {
protocol: 'http:',
hostname: 'hostname',
method: 'post',
port: port,
path: 'path',
headers: {
// POST 请求一定要加这两个参数
// charset=UTF-8 保证中文字符不乱码
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',// 不写这个参数,后台会接收不到数据
'Content-Length': Buffer.byteLength(postData , 'utf8')
}
};
var req = http.request(opt, function (res) {
// 返回的数据utf8编码
res.setEncoding('utf-8');
res.on('data', function (d) {
str += d;
}).on('end', function () {
console.log(str);
});
});
req.on('error', function (e) {
console.log('Got error: ' + e.message);
});
req.write(postData );
req.end();
Content-Type 后面需要添加对应的编码如:charset=UTF-8'