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

标签 javascript node.js express

我试图将一组文件和一些 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_photophotos 是保存在文件系统上的图像。

如何在 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/

相关文章:

javascript - 在页面加载之间保持变量

javascript - 向 Fluxpoint api 发送请求时出错

Javascript - 在网页上保存图像

mongodb - 是否可以使用 $inc 通过 Mongoose 更新子文档?

node.js - git 推送的更改未反射(reflect)在 heroku 服务器上

node.js - 返回前更新 mongoose 文档

node.js - 运行 pm2 日志错误 SyntaxError : Unexpected token

node.js - 如何使用 Bull 和 Node.js 通过后台作业处理函数?

javascript - 什么是 'tools for native modules' ?帮助新手决定是否有必要(NodeJS 安装)

javascript - 当内部 div 获得焦点时防止 div 滚动到顶部 - IE 11