繁体   English   中英

Express JS发送文件数组和json作为响应

[英]Express JS send array of files and json as response

我正在尝试将一系列文件和一些其他属性(这些属性以json格式)发送回客户端,以作为路由被点击时的一种响应。 我对Node and 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_photophotos是保存在文件系统中的图像。

如何在Node JS中实现此目标?

由于JSON不适用于传输(大量)二进制数据,因此建议将URL返回到图像文件,并由Express提供它们。

完成目录设置后,您将添加一个静态文件处理程序

app.use('/images', express.static(path.join(__dirname, 'images')));

对于您的JSON,最简单的方法是将路径(相对于网站的根目录)传递到图像文件,以便客户端可以下载它们(或构建完整的URL并以HTML格式提供)。

例如:

cover_photo: '/images/clothes/cloth1.jpg'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM