Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 获取图像到角度组件的请求返回404未找到_Node.js_Angular_Mongodb_Typescript_Express - Fatal编程技术网

Node.js 获取图像到角度组件的请求返回404未找到

Node.js 获取图像到角度组件的请求返回404未找到,node.js,angular,mongodb,typescript,express,Node.js,Angular,Mongodb,Typescript,Express,我正在尝试从我的mongodb数据库上载和检索图像。我使用multer进行图像上传,使用express和mongoose进行GET/POST请求。到目前为止,我成功地将图像上传到数据库,并使用Angular服务检索它。图像的数据,即_id、名称和化身值都由我的服务成功获取。但是,当我尝试在组件中显示图像时,浏览器控制台中会出现以下错误: GET http://localhost:3000/public/image-1617990660620.png 404 (Not Found) 我无法理解为

我正在尝试从我的mongodb数据库上载和检索图像。我使用multer进行图像上传,使用express和mongoose进行GET/POST请求。到目前为止,我成功地将图像上传到数据库,并使用Angular服务检索它。图像的数据,即_id、名称和化身值都由我的服务成功获取。但是,当我尝试在组件中显示图像时,浏览器控制台中会出现以下错误:

GET http://localhost:3000/public/image-1617990660620.png 404 (Not Found)
我无法理解为什么这条路径不正确。我的图像正在公用文件夹中提供。除了这个404错误,其他一切都正常工作

我的server.js文件如下所示:

const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const multer = require('multer');
const cors = require('cors');
const passport = require('passport');
const mongoose = require('mongoose');
const dotenv = require('dotenv');
const session = require('express-session');
const multipart = require('connect-multiparty');
const multipartMiddleware = multipart();


//import the database configuration file and connect the server to the db using mongoose
const config = require('./config/db');

mongoose.connect(config.database,{
    useNewUrlParser: true,
    useUnifiedTopology: true,
    useFindAndModify: false,
    useCreateIndex: true
});

//initialize app

const app = express();

app.use(cors());


//static files access
app.use(express.static(path.join(__dirname, 'public')));

//initialize bodyparser, passport and exress-session middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

app.use(session({
  secret: 'keyboard cat',
  resave: true,
  saveUninitialized: true,
  //cookie: { secure: true }
}));

app.use(passport.initialize());
app.use(passport.session());  


require('./config/passport')(passport);


//routes

app.use('/users', require('./routes/users')); //main route users which will lead to register and login etc.
app.use('/blogs', require('./routes/users'));
app.use('/gallery', require('./routes/users'));

//port number we use
const port = 3000;

//start server
app.listen(port,
    console.log(`Server Running in ${process.env.NODE_ENV} mode on port ${port} and database on ${config.database}`)
);
我的多重确认以及我的GET和POST请求:

const express = require('express');
const router = express.Router();
const bcrypt = require('bcryptjs');
const passport = require('passport');
const jwt = require('jsonwebtoken');
const multer = require('multer');
const User = require('../models/User');
const Post = require('../models/Post');
const Favorites = require('../models/Favorites');
const Gallery = require('../models/Gallery');
const config = require('../config/db');
const path = require('path');

// Multer Storage


const storage = multer.diskStorage({
    destination: (req, file, cb) => {
      cb(null, 'public');
    },
    filename: (req, file, cb) => {
      console.log(file);
      var filetype = '';
      if(file.mimetype === 'image/gif') {
        filetype = 'gif';
      }
      if(file.mimetype === 'image/png') {
        filetype = 'png';
      }
      if(file.mimetype === 'image/jpeg') {
        filetype = 'jpg';
      }
      cb(null, 'image-' + Date.now() + '.' + filetype);
    }
});

const upload = multer({storage: storage});


router.post('/archive', upload.single('image'), async function(req, res, next) {
  const name = req.file.filename;
  const avatar = 'http://localhost:3000/public/' + req.file.filename;
  const gallery = new Gallery({
    name,
    avatar
  });
  const createdGallery = await gallery.save();
  res.status(200).json({
    gallery: {
      ...createdGallery._doc
    }
  });
  console.log(createdGallery);
  });

router.get("/archive", async (req, res, next) => {
  const images = await Gallery.find();
  res.status(200).json({ images });
});
我的组件的HTML:

<app-header></app-header>
<h1>All Images</h1>
<hr />
<div *ngIf="images?.length > 0">
  <div *ngFor="let image of images" class="image">
    <img [src]="image.avatar" [alt]="image.name" />
    <div>
      <span>{{ image.name }}</span>
    </div>
  </div>
</div>

有人能告诉我是什么导致了这个错误以及我如何解决它吗?我对MEAN Stack还比较陌生,非常感谢您的指导和帮助。非常感谢。

错误:Angular组件找不到任何名为“public”的文件夹来访问图像,因为我没有在我的server.js中指定要访问该文件夹的任何路径

解决方案:添加以下代码行:

app.use('/public', express.static(path.join('public')));
这一行确保使用url
http://localhost:3000/
我可以访问公用文件夹。否则,它只是为服务静态文件而设置的

app.use('/public', express.static(path.join('public')));