【问题标题】:How to return an absolute path if i have only a relative path in NestJS?如果我在 NestJS 中只有相对路径,如何返回绝对路径?
【发布时间】:2021-05-23 04:52:55
【问题描述】:

我有一个带有 typeORM 驱动程序 (MySQL) 的 NestJS 项目。当用户上传照片时,服务器将文件保存在公共目录中,并在数据库中保存相对路径:/public/user22.png

当用户发送请求以获取有关其个人资料的信息时,服务器应返回绝对路径。 用户也可以获得用户列表。

我可以编辑用户配置文件的返回对象。但我不想使用循环来编辑用户列表。有没有最优算法来解决这个问题?

【问题讨论】:

  • I don't want to use cycle 是什么意思?
  • @HugoSohm 我的意思是 const _news = this.newsRepo.find({}); const newsCorrectImageUrl = _news.map((news) = ({ ...news, photo: "example.com" + news.photo, //
  • 我明白了,我给你写个答案给你解释一下这两种解决方案

标签: javascript typescript nestjs typeorm


【解决方案1】:

您有两种解决方案可以将相对路径转换为绝对路径。

第一个选项是根据名为 apiBaseUrl 的环境变量附加前端使用的每个图像。

const users = await axios.get('/users');

<img src={`${process.env.NEXT_PUBLIC_API_BASEURL}/${users.image}`}/>

当然,如果您多次使用它,它将开始未优化。

第二个选项是在返回结果之前创建修改,以使用名为 baseUrl 的环境变量修改您的 photo 值。

const result: exampleEntity = this.exampleRepository.find();

const newExample: exampleEntity = this.exampleRepository.create({
      ...result,
      photo: this.configService.baseUrl + result.photo,
    });

return entityExample;

如果暂时不处理环境变量,可以阅读configuration documentation

【讨论】:

    猜你喜欢
    • 2010-09-05
    • 1970-01-01
    • 1970-01-01
    • 2010-09-21
    • 2014-03-16
    • 1970-01-01
    • 2012-01-11
    • 2010-09-15
    • 2013-04-17
    相关资源
    最近更新 更多