【问题标题】:Node Express sending image files with JSON as API responseNode Express 发送带有 JSON 的图像文件作为 API 响应
【发布时间】:2020-11-27 23:28:06
【问题描述】:

如何将 json 与图片文件一起以 express 方式发送?

我了解到您使用 res.sendFile 提供图片

const path = require('path');

app.get('/image/:filename', (req, res, next) => {
  res.type('png');
  res.sendFile(
    path.resolve(`${path.join(__dirname, './data/images')}/${req.params.fileName}`)
  );
});

但是,如果您想在图像中包含 json 怎么办?例如,如果您提供用户的个人资料数据 - 名称、信息等个人资料图片。

const path = require('path');

app.get('/user/:id', async (req, res, next) => {
  const { id } = req.params;
  let user;
  try {
    user = await userService.getUser(id);
  } catch (err) {
    return next(err);
  }

  /* user:
   * {
   *   name: "Dash",
   *   location: "Chicago",
   *   profilePicture: '5c751e73-a7bc-47c4-b2a5-4ac902e7a2ce.png'
   * }
   */

  // what next????
});

你做不到

  res.type('png');
  res.sendFile(path.resolve(`${path.join(__dirname, './data/images')}/${user.profilePicture}`));

res.send(json)。那么如何同时发送呢?

【问题讨论】:

    标签: javascript node.js express http


    【解决方案1】:

    理想情况下,您不需要。

    JSON 是纯文本格式。如果要在 JSON 中包含二进制资源,则必须使用 base64 对其进行编码。这使它与文本兼容,但增加了 33% 的大小,同时浪费 CPU 和内存进行编码和解码。

    通常的方法是简单地有两个 HTTP 请求。将有一个用于您的 Node.js API 服务器,另一个用于个人资料图片图像。由于很多原因,这更好。它解决了您当前的问题,同时还允许您在应用程序之外托管图像,并利用 CDN 和缓存。

    【讨论】:

    • 当然,您可以在 JSON 中包含图片的 URL。
    猜你喜欢
    • 2013-07-05
    • 1970-01-01
    • 2017-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-21
    • 2014-02-10
    相关资源
    最近更新 更多