我正在编写一些代理服务器代码来拦截请求(由用户单击浏览器窗口中的链接发起)并将请求转发到第三方文件服务器。然后我的代码得到响应并将其转发回浏览器。根据文件的 mime 类型,我想以两种方式之一处理文件服务器的响应:
- 如果文件是图像,我想将用户发送到显示图像的新页面,或者
- 对于所有其他文件类型,我只希望浏览器处理接收它(通常是下载)。
我的节点堆栈包括 Express+bodyParser、Request.js、EJS 和 Passport。这是基本代理代码以及一些需要大量帮助的伪代码。(过错!)
app.get('/file', ensureLoggedIn('/login'), function(req,res) {
var filePath = 'https://www.fileserver.com/file'+req.query.fileID,
companyID = etc…,
companyPW = etc…,
fileServerResponse = request.get(filePath).auth(companyID,companyPW,false);
if ( fileServerResponse.get('Content-type') == 'image/png') // I will also add other image types
// Line above yields TypeError: Object #<Request> has no method 'get'
// Is it because Express and Request.js aren't using compatible response object structures?
{
// render the image using an EJS template and insert image using base64-encoding
res.render( 'imageTemplate',
{ imageData: new Buffer(fileServerResponse.body).toString('base64') }
);
// During render, EJS will insert data in the imageTemplate HTML using something like:
// <img src='data:image/png;base64, <%= imageData %>' />
}
else // file is not an image, so let browser deal with receiving the data
{
fileServerResponse.pipe(res); // forward entire response transparently
// line above works perfectly and would be fine if I only wanted to provide downloads.
}
})
我无法控制文件服务器,文件不一定有文件后缀,所以我需要获取它们的 MIME 类型。如果有更好的方法来执行此代理任务(例如通过将文件服务器的响应临时存储为文件并检查它),我会全力以赴。此外,如果有帮助,我可以灵活地添加更多模块或中间件。谢谢!