图像未显示在 hbs/nodejs 中

我正在尝试使用 NodeJs 和 express-handlebars 创建一个简单的 Web 应用程序。 但是图像在我使用把手渲染的 html 页面中没有正确显示。

以下是我的应用程序结构

MyApp 是根目录

-images
-views
  -layouts
    -main.hbs
  -home.hbs
-index.js
-package.json

project structure

我的 index.js 包含以下代码

const express = require('express');
const exphbs = require('express-handlebars');

const app = express();

//Setting default layout and extension name
app.engine('hbs',exphbs({
defaultLayout: 'main',extname: '.hbs'
}));

//providing path for images 
app.use(express.static("images"));

//Setting view engine 
app.set('view engine','hbs');

//get method for landing page
app.get('/',(req,res)=>{
  res.render('landing')
})

//get method for home page
app.get('/home',res) =>{
  res.render('home');
})
//Staring server
app.listen(8080,() =>{
   console.log("Server started successfully on port 8080");
});

home.hbs 包含如下

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <img src="/home/vishu/Desktop/WebTest/ECom/images/apple.jpg"  alt="Apple product set">
</body>
</html>

我应该怎么做才能解决上述问题

xzgfzcnk 回答:图像未显示在 hbs/nodejs 中

import 'dart:async';

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Rich Text Animation',theme: ThemeData(
        primarySwatch: Colors.blue,),home: MyHomePage(title: 'Rich Text Animation'),);
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key,required this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  StreamController<List<TextSpan>> _streamController =
      StreamController.broadcast();
  static const DELAY = Duration(milliseconds: 100); 

  @override
  void initState() {
    super.initState();
    _animate();
  }

  void _animate() {
    final _allSpans = [
      TextSpan(text: 'This is a ',style: TextStyle(color: Colors.white)),TextSpan(text: 'title',style: TextStyle(color: Colors.red)),];
    Duration _delay = Duration(seconds: 1);
    _allSpans.forEach((span) {
      for (int i = 0; i < (span.text?.length ?? 0); i++) {
        Future.delayed(_delay,() {
          _streamController.add([
            ..._allSpans.sublist(0,_allSpans.indexOf(span)),TextSpan(text: span.text!.substring(0,i + 1),style: span.style)
          ]);
        });
        _delay += DELAY;
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),body: Container(
        color: Colors.green.shade700,child: Center(
          child: StreamBuilder<List<TextSpan>>(
            builder: (context,snapshot) {
              if (snapshot.hasData) {
                return RichText(
                  text: TextSpan(children: snapshot.data),);
              }
              return CircularProgressIndicator();
            },stream: _streamController.stream,floatingActionButton: FloatingActionButton(
        child: Icon(Icons.animation),onPressed: () {
          _animate();
        },);
  }

  @override
  void dispose() {
    _streamController.close();
    super.dispose();
  }
}

对于图片网址,使用服务器上托管的图片获取路径。

let options = {
            dotfiles: "ignore",//allow,deny,ignore
            etag: true,extensions: ["htm","html"],index: false,//to disable directory indexing
            maxAge: "7d",redirect: false,setHeaders: function (res: any,path: any,stat: any) {
                //add this header to all static responses
                res.set("x-timestamp",Date.now());
            }
        };

//process.cwd will fetch from the current working directory and serve images over the server
app.use(express.static(`${process.cwd()}/images`,options));
//it will set the html path that would get served from /views 
app.set('views',express.static(process.cwd() + '/views'));
//it will set the engine
app.set('view engine','hbs');
        
//BASE URL
`${BASE.URL}/images/Pamlogo.png`
本文链接:https://www.f2er.com/1112.html

大家都在问