简体   繁体   English

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

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

I am trying to send back to the client an array of files, and a few more properties which are in json format as one response when a route is hit. 我正在尝试将一系列文件和一些其他属性(这些属性以json格式)发送回客户端,以作为路由被点击时的一种响应。 I am relatively new to Node and Express but I have not found anyway to handle this. 我对Node and Express相对较新,但是无论如何我都没有找到解决方法。 I know (and have successfully tried) sending one file back to the client. 我知道(并且已经成功尝试过)将一个文件发送回客户端。 The kind of response I want to send back should look like this 我想发回的回复应该是这样的

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 and photos are images saved on the file system. cover_photophotos是保存在文件系统中的图像。

How can I achieve this in Node JS? 如何在Node JS中实现此目标?

Since JSON isn't great to transfer (a lot of) binary data, I would suggest returning URL's to the image files, and having them served by Express. 由于JSON不适用于传输(大量)二进制数据,因此建议将URL返回到图像文件,并由Express提供它们。

Taking your directory setup, you'd add a static file handler : 完成目录设置后,您将添加一个静态文件处理程序

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

For your JSON, the easiest then would be to pass the paths (relative to the website's root) to the image files, so the client can download them (or build a full URL and serve them in HTML). 对于您的JSON,最简单的方法是将路径(相对于网站的根目录)传递到图像文件,以便客户端可以下载它们(或构建完整的URL并以HTML格式提供)。

For instance: 例如:

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

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

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