我试图将一组文件和一些 json 格式的属性发送回客户端,作为命中路由时的一个响应。我对 Node 和 Express 比较陌生,但我还没有找到解决这个问题的方法。我知道(并且已经成功尝试过)将一个文件发送回客户端。我想要发回的响应应该是这样的
res.send([
{
name:'Floral dresses',
date_added:'2016-10-11 06:52:39',
designer:'Victoria',
cover_photo: path.join(__dirname, '/images', '/clothes', '/cloth1.jpg'),
photos: [
path.join(__dirname, '/images', '/clothes', '/cloth1.jpg'),
path.join(__dirname, '/images', '/clothes', '/cloth2.jpg'),
path.join(__dirname, '/images', '/clothes', '/cloth3.jpg')
]
},
{
name:'Vintage Dresses',
date_added:'2016-02-08 18:12:09',
designer:'Victoria',
cover_photo: path.join(__dirname, '/images', '/clothes', '/cloth1.jpg'),
photos: [
path.join(__dirname, '/images', '/clothes', '/cloth1.jpg'),
path.join(__dirname, '/images', '/clothes', '/cloth2.jpg'),
path.join(__dirname, '/images', '/clothes', '/cloth3.jpg')
]
}
];
cover_photo
和 photos
是保存在文件系统上的图像。
如何在 Node JS 中实现这一点?
最佳答案
由于 JSON 不太适合传输(大量)二进制数据,因此我建议将 URL 返回到图像文件,并由 Express 提供服务。
在进行目录设置时,您需要添加 static file handler :
app.use('/images', express.static(path.join(__dirname, 'images')));
对于 JSON,最简单的方法是将路径(相对于网站的根目录)传递到图像文件,以便客户端可以下载它们(或构建完整的 URL 并以 HTML 形式提供它们)。
例如:
cover_photo: '/images/clothes/cloth1.jpg'
关于javascript - Express JS 发送文件数组和 json 作为响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39309349/