【问题标题】:Nodejs does not display the imagesNodejs不显示图像
【发布时间】:2019-12-02 21:22:22
【问题描述】:

我有一个非常简单的 nodejs 应用程序,它正在呈现一个 HTML 页面。

我的目录结构:

C:\Users\user_id\Desktop\keys\nodejs\node-v12.13.1-win-x64
12/02/2019  05:08 PM    <DIR>          .
12/02/2019  05:08 PM    <DIR>          ..
11/19/2019  01:35 PM            54,162 CHANGELOG.md
12/02/2019  06:23 PM    <DIR>          images
12/02/2019  06:27 PM               353 index.html
10/23/2019  11:31 AM             2,953 install_tools.bat
11/19/2019  01:35 PM            78,655 LICENSE
11/19/2019  01:50 PM        28,787,352 node.exe
10/10/2019  11:31 AM               702 nodevars.bat
10/10/2019  11:31 AM            10,630 node_etw_provider.man
12/02/2019  05:06 PM    <DIR>          node_modules
10/10/2019  11:31 AM               930 npm
10/10/2019  11:31 AM               483 npm.cmd
10/10/2019  11:31 AM               922 npx
10/10/2019  11:31 AM               539 npx.cmd
11/19/2019  01:35 PM            26,931 README.md
12/02/2019  05:07 PM             1,765 server.js
              13 File(s)     28,966,377 bytes
               4 Dir(s)  108,750,237,696 bytes free

html页面

<!doctype HTML>
<html>
  <head>
    <title>
      Index
    </title>
  </head>
  <body>
    <h1>
      <p>Hello! Image
        <br><br>
          <img src="http://localhost:3000/images/img_chania.jpg" alt="Flowers in Chania" width="660" height="345">
      </p>
    </h1>
    <h1>
      Bye Bye! Image
    </h1>
  </body>
</html>

server.js 文件

const express = require('express')
const app = express()
const path = require('path')
const port = 3000

/*
* Default route for the web app
*/
app.get('/', (req, res) => res.send('Welcome'))

/*
* Route to render HTML Page
*/
app.get('/renderHTML', (req, res) => {
    res.sendFile('./index.html', {
        root: path.join(__dirname, './')
    })
})

app.listen(port, () => console.log(`App listening on port ${port}!`))

所有图片都存储在images目录中。

如果我只是渲染 index.html 页面,图像是可见的。 当我们通过节点应用程序运行它时,图像只是不显示。

这似乎是路径的问题,当使用检查并单击控制台进行调试时,它给了我一个 404 错误。

非常感谢任何帮助

谢谢

【问题讨论】:

  • src="http://localhost:3000/images/img_chania.jpg" 不正确。您需要在没有localhost:3000 的情况下提供图像的位置
  • @stud3nt — 虽然相对 URL 通常更好,但在这里使用绝对 URL 不是问题。
  • 与您的问题无关,但您似乎正在使用 nodejs 安装文件夹来保存脚本,这不是一个好主意,请使用其他文件夹。
  • @Quentin 同意,图片文件夹也必须共享。

标签: javascript node.js node-modules


【解决方案1】:

你有一个/ 的路由,你有一个/renderHTML 的路由。

你没有/images 的路由,所以它当然会给你一个 404。

使用the static module as described in the Getting Started guide:

app.use("/images", express.static('images'))

【讨论】:

    【解决方案2】:

    静态图片必须使用静态中间件。查看这篇文章的详细信息。 http://expressjs.com/en/starter/static-files.html#serving-static-files-in-express

    app.use(express.static('public'))

    【讨论】:

      猜你喜欢
      • 2015-05-28
      • 1970-01-01
      • 2014-02-09
      • 1970-01-01
      • 1970-01-01
      • 2017-06-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多