URL重写不能与iframe expressjs一起使用

我正在尝试使用express来重写iframe的URL。

类似的代码工作正常在我的public文件夹中可用的文件(这表示感谢server.use(express['static'](__dirname + '/public'server.use(express['static'](__dirname + '/public' )。

玉代码:

 iframe(width="560", height="315", src="/videos/9bZkp7q19f0", frameborder="0", allowfullscreen=true) 

快递代码:

 server.use(function(req, res, next) { if (/videos/.test(req.url)) { req.url = req.url.replace("videos", "embed"); req.url = "www.youtube.com" + req.url; } next(); }); 

添加console.log(req.url)显示正确的URL(www.youtube.com/embed/9bZkp7q19f0),但是会logging404错误。

提前致谢。

你不能只改变req.url并期望客户端从那里实际检索数据。 你需要的是一个代理或redirect。

redirect将强制iframeredirect到youtube.com

 res.redirect('http://www.youtube.com' + req.url.replace('videos', 'embed')); 

代理实际上会从你的服务器请求这个页面,下载这个内容,然后返回给客户端(你可以使用这个请求 )

 req.pipe(require('request')('http://www.youtube.com' + req.url.replace('videos', 'embed'))).pipe(res);