1.页面ajax的请求
$.ajax({
async: false,
url: 'http://localhost:8080/downloadVideos',//跨域的dns/document!searchJSONResult.action,
type: "GET",
dataType: 'jsonp',
jsonp: 'jsoncallback',
jsonpCallback: "cb",//自定义返回函数的名称,要与服务端保持一致
data: {
id:ID,
user:user
},
timeout: 5000,
success: function (json) {
$(data).css("background","red");
alert(json);
}
});
2.服务端nodeJS的返回
app.get('/downloadVideos', function (req, res, next) {
var random = new Date().getTime();
var url = "https://savemedia.com/generate/";
var videosID = req.query.id;
superagent
.get(url + videosID + "?random=" + random)
.end(function (err, sres) { // callback
// 常规的错误处理
if (err) {
return next(err);
}
var obj = JSON.parse(sres.text);
var url = obj.download.watch[0].url;
var videoName = new Date().getTime();
downloadFile(url, "../public/videos/" + videoName + ".mp4", function (err) {
if (err) {
return next(err);
// console.log(videoName + ".mp4" + '下载完毕');
});
var videoUrl = 'http://**.**.**.**:8080/videos/' + videoName + '.mp4';
res.send("cb(" + JSON.stringify(videoUrl) + ")");
});
});
//文件下载function downloadFile(uri, filename, callback) {
var stream = fs.createWriteStream(filename);
request(uri).pipe(stream).on('close', callback);
}