【问题标题】:vite react dynamic image urlvite react 动态图片 url
【发布时间】:2021-10-01 17:41:08
【问题描述】:

大家好,我遇到了 vite react 动态图像 url 无法正确加载的问题,这就是我的组件

 <Flex>
      {data?.map((tag) => (
        <Box key={tag._id}>
          <Image w="150px" h="150px" src={`http:localhost:5000/${tag.imageUrl}`}></Image>
        </Box>
      ))}
    </Flex>

当我检查网络选项卡时,我看到客户端的 url 已添加到图像 url 中

http://localhost:3000/localhost:5000/uploads/1623642756947--Capture.PNG

在创建 React 应用程序时,也许我们可以使用 reqiure() 来修复它,但我不知道如何在 vite 中修复它并添加 reqiure() 会引发错误

【问题讨论】:

    标签: reactjs vite


    【解决方案1】:

    当我检查网络选项卡时,我看到客户端的 url 已添加到图像 url http://localhost:3000/localhost:5000/uploads/1623642756947--Capture.PNG

    ? 这是因为在 vite导入静态资产会在服务时返回解析的公共 URL

    摘自官方文档(根据您的问题改编)

    • 例如,http//:localhost:5000/${tag.imageUrl} 在开发过程中将是/http:localhost:5000/uploads/1623642756947--Capture.PNG

    • 并在生产版本中成为/assets/http:localhost:5000/uploads/1623642756947--Capture.PNG

    解决方案是使用vite configserver.proxy 选项将您的动态资产请求转发 到所需的服务器,在vite.config.js 添加:

      server: {
        proxy: {
          // forward `/uploads/` endpoint to -> `http://localhost:5000/uploads/`
          '^/uploads': {
            target: 'http://localhost:5000/'
          }
        }
      }
    

    所以在你的组件中,Image 应该这样声明:

    &lt;Image w="150px" h="150px" src={`${tag.imageUrl}`}&gt;&lt;/Image&gt;

    现在当你击球时 http://localhost:3000/uploads/1623642756947--Capture.PNG

    资产(图片)将从http://localhost:5000/uploads/1623642756947--Capture.PNG加载

    您可以获取更多关于Static Assets Handlingherevite proxy optionshere的信息。

    解决方案已经过测试并且有效✔

    【讨论】:

      猜你喜欢
      • 2020-04-27
      • 2021-04-20
      • 1970-01-01
      • 2017-12-08
      • 1970-01-01
      • 2018-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多