var _ = require('lodash');
var request = require("request");
/*
@LM 2017-02-16
node端代理浏览器路由 解决浏览器跨域问题
demo:
router.post('/proxy_http',proxy_routes);
condition = {
url:'',//接口地址 (必填)
method:''//接口方式 (看接口需求)
host:'',//
form:{} post请求参数
}
*/
exports.proxy_routes = function(req, res, next) {
/*处理get或者post请求的req参数*/
var condition = _.assign(req.body || {}, req.query || {});
if(!condition.url){
return next({status:,message:'not defind url'})
}
if(condition.host){
req.headers.host = condition.host;
}
var opts = {
url: condition.url,
method: condition.method||'GET',
// headers: req.headers,
form:condition.form||{}
};
var ts = Date.now();
console.log('proxy_routes', opts, ts, "请求开始--");
request(opts,function(err, response, body) {
if(err){
console.log('proxy_routes', opts, ts, "请求异常--err:" + err, (Date.now() - ts) + 'ms');
return next(err);
}
console.log('proxy_routes', opts, ts, "请求正常--response.statusCode:" + response.statusCode, (Date.now() - ts) + 'ms');
try{
res.json(JSON.parse(body));
}catch(e){
res.json(body);
}
});
};