node代理下载的问题
我有一个做下载的操作,但因需求,需要先经过node做一次转发再请求到远程服务。我的代码如下:
var http = require("http");
var querystring = require("querystring");
var url = require('url');
var proxyconfig = require("../config/proxy");
exports.ajax = function (req, res) {
var ajaxUrl = req.body.url;
var ajaxType = req.body.type;
var ajaxData = req.body.data || "";
var ajaxContentType = (req.body.contentType || "application/x-www-form-urlencoded") +"; charset=utf-8";
var urlObj = {
hostname: proxyconfig.hostname,
port: proxyconfig.port,
path: ajaxUrl
};
if(ajaxUrl.indexOf("http") >= 0){
urlObj = url.parse(ajaxUrl);
}
var options = {
hostname: urlObj.hostname,
port: urlObj.port,
path: urlObj.path,
method: ajaxType,
headers: {
'Content-Type': ajaxContentType,
'Content-Length': Buffer.byteLength(ajaxData, 'utf8')
}
};
var ajaxReq = http.request(options, function (ajaxRes) {
ajaxRes.setEncoding('utf8');
ajaxRes.pipe(res);
});
ajaxReq.on('error', function (e) {
console.log('problem with request: ' + e.message);
res.json({
ok: false,
msg: "请求数据异常!",
extmsg: e.message
});
});
if(ajaxData){
ajaxReq.write(ajaxData);
}
ajaxReq.end();
};
但是现在的问题是,我在浏览器做了下载请求后,只能获取一个乱码的文件,而无法得到正确的文件。请问怎么处理这个问题?