core. js: 5873 ОШИБКА TypeError: Невозможно прочитать свойство 'filename' из undefined - PullRequest
0 голосов
/ 09 апреля 2020

Я пытаюсь сохранить некоторые изображения на моем Node.JS сервере и прочитать их из Angular клиента со следующими кодами:

image.ts:

export class Image {
    fieldname: string;
    originalname: string;
    encoding: string;
    mimetype: string;
    destination: string;
    filename: string;
    path: string;
    size: number;
}

image. service.ts:

export class ImagesService {

  constructor(private http: HttpClient,
    private processHTTPMsgService: ProcessHTTPMsgService) { }

  getImages(): Observable<Image[]> {
    return this.http.get<Image[]>(baseURL + 'images')
      .pipe(catchError(this.processHTTPMsgService.handleError));
  }

}

моделей / изображений. js:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var imageSchema = new Schema({
  fieldname: {
      type: String
  },
  originalname: {
      type: String
  },
  encoding: {
      type: String
  },
  mimetype: {
      type: String
  },
  destination: {
      type: String
  },
  filename: {
      type: String
  },
  path: {
      type: String
  },
  size:{
    type: Number
  }
}, {
  timestamps: true
});

var Images = mongoose.model('Image', imageSchema);
module.exports = Images ;

imagesRouter. js:

imagesRouter.route('/')
.get(cors.cors, (req,res,next) => {
    Images.find({})
    .then((images) => {
        res.statusCode = 200;
        res.setHeader('Content-Type', 'application/json');
        res.json(images);

    }, (err) => next(err))
    .catch((err) => next(err));
})



module.exports = imagesRouter;

И uploadRouter. js:

const express = require('express');
const bodyParser = require('body-parser');
const authenticate = require('../authenticate');
const multer = require('multer');
const cors = require('./cors');
const Images = require('../models/images');


const storage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, 'public/images');
    },

    filename: (req, file, cb) => {
        cb(null, file.originalname)
    }
});

const imageFileFilter = (req, file, cb) => {
    if(!file.originalname.match(/\.(jpg|jpeg|png|gif)$/)) {
        return cb(new Error('You can upload only image files!'), false);
    }
    cb(null, true);
};

const upload = multer({ storage: storage, fileFilter: imageFileFilter});

const uploadRouter = express.Router();
uploadRouter.use(bodyParser.json());

uploadRouter.route('/')

.post(cors.corsWithOptions, authenticate.verifyUser, authenticate.verifyAdmin, upload.single('imageFile'),
 (req, res, next) => {
    Images.create(req.file)
    .then((image) => {
        res.statusCode = 200;
        res.setHeader('Content-Type', 'application/json');
        res.json(req.file);
    }, (err) => next(err))
    .catch((err) => next(err));


})

Я могу успешно загрузить изображения, используя Postman, и получаю результат, подобный следующему:

{
    "fieldname": "imageFile",
    "originalname": "home_header.jpg",
    "encoding": "7bit",
    "mimetype": "image/jpeg",
    "destination": "public/images",
    "filename": "home_header.jpg",
    "path": "public\\images\\home_header.jpg",
    "size": 58277
}

И он будет сохранен в MongoDB следующим образом:

{
        "_id" : ObjectId("5e9051503af5a25cc487abe8"),
        "fieldname" : "imageFile",
        "originalname" : "home_header.jpg",
        "encoding" : "7bit",
        "mimetype" : "image/jpeg",
        "destination" : "public/images",
        "filename" : "home_header.jpg",
        "path" : "public\\images\\home_header.jpg",
        "size" : 58277,
        "createdAt" : ISODate("2020-04-10T10:58:24.710Z"),
        "updatedAt" : ISODate("2020-04-10T10:58:24.710Z"),
        "__v" : 0
}
{
        "_id" : ObjectId("5e90519c40aea44ca84df4ca"),
        "fieldname" : "imageFile",
        "originalname" : "logo.png",
        "encoding" : "7bit",
        "mimetype" : "image/png",
        "destination" : "public/images",
        "filename" : "logo.png",
        "path" : "public\\images\\logo.png",
        "size" : 18534,
        "createdAt" : ISODate("2020-04-10T10:59:40.979Z"),
        "updatedAt" : ISODate("2020-04-10T10:59:40.979Z"),
        "__v" : 0
}

Но я не знаю, в чем заключается проблема, я могу увидеть изображения на моем веб-сайте и получить эти сообщения об ошибках:

core.js:5873 ERROR TypeError: Cannot read property 'filename' of undefined
    at HeaderComponent_Template (header.component.html:2)
    at executeTemplate (core.js:11930)
    at refreshView (core.js:11777)
    at refreshComponent (core.js:13217)
    at refreshChildComponents (core.js:11508)
    at refreshView (core.js:11829)
    at refreshComponent (core.js:13217)
    at refreshChildComponents (core.js:11508)
    at refreshView (core.js:11829)
    at renderComponentOrTemplate (core.js:11903)
defaultErrorLogger @ core.js:5873
handleError @ core.js:5926
(anonymous) @ core.js:42696
invoke @ zone-evergreen.js:365
run @ zone-evergreen.js:124
runOutsideAngular @ core.js:41093
tick @ core.js:42693
_loadComponent @ core.js:42733
bootstrap @ core.js:42659
(anonymous) @ core.js:42251
_moduleDoBootstrap @ core.js:42247
(anonymous) @ core.js:42202
invoke @ zone-evergreen.js:365
onInvoke @ core.js:41257
invoke @ zone-evergreen.js:364
run @ zone-evergreen.js:124
(anonymous) @ zone-evergreen.js:851
invokeTask @ zone-evergreen.js:400
onInvokeTask @ core.js:41235
invokeTask @ zone-evergreen.js:399
runTask @ zone-evergreen.js:168
drainMicroTaskQueue @ zone-evergreen.js:570
Promise.then (async)
scheduleMicroTask @ zone-evergreen.js:553
scheduleTask @ zone-evergreen.js:389
scheduleTask @ zone-evergreen.js:211
scheduleMicroTask @ zone-evergreen.js:231
scheduleResolveOrReject @ zone-evergreen.js:841
then @ zone-evergreen.js:967
bootstrapModule @ core.js:42232
./src/main.ts @ main.ts:11
__webpack_require__ @ bootstrap:79
0 @ main.ts:12
__webpack_require__ @ bootstrap:79
checkDeferredModules @ bootstrap:45
webpackJsonpCallback @ bootstrap:32
(anonymous) @ main.js:1
core.js:40451 Angular is running in the development mode. Call enableProdMode() to enable the production mode.
core.js:5873 ERROR TypeError: Cannot read property 'filename' of undefined
    at HomeComponent_Template (home.component.html:3)
    at executeTemplate (core.js:11930)
    at refreshView (core.js:11777)
    at refreshComponent (core.js:13217)
    at refreshChildComponents (core.js:11508)
    at refreshView (core.js:11829)
    at refreshDynamicEmbeddedViews (core.js:13142)
    at refreshView (core.js:11800)
    at refreshComponent (core.js:13217)
    at refreshChildComponents (core.js:11508)
defaultErrorLogger @ core.js:5873
handleError @ core.js:5926
(anonymous) @ core.js:42696
invoke @ zone-evergreen.js:365
run @ zone-evergreen.js:124
runOutsideAngular @ core.js:41093
tick @ core.js:42693
(anonymous) @ core.js:42533
invoke @ zone-evergreen.js:365
onInvoke @ core.js:41257
invoke @ zone-evergreen.js:364
run @ zone-evergreen.js:124
run @ core.js:41032
next @ core.js:42530
schedulerFn @ core.js:36857
__tryOrUnsub @ Subscriber.js:183
next @ Subscriber.js:122
_next @ Subscriber.js:72
next @ Subscriber.js:49
next @ Subject.js:39
emit @ core.js:36819
checkStable @ core.js:41171
onHasTask @ core.js:41278
hasTask @ zone-evergreen.js:420
_updateTaskCount @ zone-evergreen.js:441
_updateTaskCount @ zone-evergreen.js:264
runTask @ zone-evergreen.js:185
drainMicroTaskQueue @ zone-evergreen.js:570
Promise.then (async)
scheduleMicroTask @ zone-evergreen.js:553
scheduleTask @ zone-evergreen.js:389
scheduleTask @ zone-evergreen.js:211
scheduleMicroTask @ zone-evergreen.js:231
scheduleResolveOrReject @ zone-evergreen.js:841
then @ zone-evergreen.js:967
bootstrapModule @ core.js:42232
./src/main.ts @ main.ts:11
__webpack_require__ @ bootstrap:79
0 @ main.ts:12
__webpack_require__ @ bootstrap:79
checkDeferredModules @ bootstrap:45
webpackJsonpCallback @ bootstrap:32
(anonymous) @ main.js:1
home:1 [Intervention] Slow network is detected. See https://www.chromestatus.com/feature/5636954674692096 for more details. Fallback font will be used while loading: http://localhost:4200/fontawesome-webfont.woff2?v=4.7.0
home:1 Access to XMLHttpRequest at 'https://localhost:3443/images/' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
core.js:5873 ERROR TypeError: Cannot read property 'filename' of undefined
    at HomeComponent_Template (home.component.html:3)
    at executeTemplate (core.js:11930)
    at refreshView (core.js:11777)
    at refreshComponent (core.js:13217)
    at refreshChildComponents (core.js:11508)
    at refreshView (core.js:11829)
    at refreshDynamicEmbeddedViews (core.js:13142)
    at refreshView (core.js:11800)
    at refreshComponent (core.js:13217)
    at refreshChildComponents (core.js:11508)
defaultErrorLogger @ core.js:5873
handleError @ core.js:5926
(anonymous) @ core.js:42696
invoke @ zone-evergreen.js:365
run @ zone-evergreen.js:124
runOutsideAngular @ core.js:41093
tick @ core.js:42693
(anonymous) @ core.js:42533
invoke @ zone-evergreen.js:365
onInvoke @ core.js:41257
invoke @ zone-evergreen.js:364
run @ zone-evergreen.js:124
run @ core.js:41032
next @ core.js:42530
schedulerFn @ core.js:36857
__tryOrUnsub @ Subscriber.js:183
next @ Subscriber.js:122
_next @ Subscriber.js:72
next @ Subscriber.js:49
next @ Subject.js:39
emit @ core.js:36819
checkStable @ core.js:41171
onLeave @ core.js:41332
onInvokeTask @ core.js:41241
invokeTask @ zone-evergreen.js:399
runTask @ zone-evergreen.js:168
invokeTask @ zone-evergreen.js:481
invokeTask @ zone-evergreen.js:1596
globalZoneAwareCallback @ zone-evergreen.js:1622
error (async)
customScheduleGlobal @ zone-evergreen.js:1735
scheduleTask @ zone-evergreen.js:386
onScheduleTask @ zone-evergreen.js:273
scheduleTask @ zone-evergreen.js:379
scheduleTask @ zone-evergreen.js:211
scheduleEventTask @ zone-evergreen.js:237
(anonymous) @ zone-evergreen.js:1907
(anonymous) @ http.js:2604
_trySubscribe @ Observable.js:42
subscribe @ Observable.js:28
subscribeToResult @ subscribeToResult.js:9
_innerSub @ mergeMap.js:59
_tryNext @ mergeMap.js:53
_next @ mergeMap.js:36
next @ Subscriber.js:49
(anonymous) @ subscribeToArray.js:3
_trySubscribe @ Observable.js:42
subscribe @ Observable.js:28
call @ mergeMap.js:21
subscribe @ Observable.js:23
call @ filter.js:13
subscribe @ Observable.js:23
call @ map.js:16
subscribe @ Observable.js:23
call @ catchError.js:16
subscribe @ Observable.js:23
ngOnInit @ header.component.ts:41
callHook @ core.js:3937
callHooks @ core.js:3901
executeInitAndCheckHooks @ core.js:3842
refreshView @ core.js:11795
refreshComponent @ core.js:13217
refreshChildComponents @ core.js:11508
refreshView @ core.js:11829
renderComponentOrTemplate @ core.js:11903
tickRootContext @ core.js:13379
detectChangesInRootView @ core.js:13413
detectChanges @ core.js:15093
tick @ core.js:42683
_loadComponent @ core.js:42733
bootstrap @ core.js:42659
(anonymous) @ core.js:42251
_moduleDoBootstrap @ core.js:42247
(anonymous) @ core.js:42202
invoke @ zone-evergreen.js:365
onInvoke @ core.js:41257
invoke @ zone-evergreen.js:364
run @ zone-evergreen.js:124
(anonymous) @ zone-evergreen.js:851
invokeTask @ zone-evergreen.js:400
onInvokeTask @ core.js:41235
invokeTask @ zone-evergreen.js:399
runTask @ zone-evergreen.js:168
drainMicroTaskQueue @ zone-evergreen.js:570
Promise.then (async)
scheduleMicroTask @ zone-evergreen.js:553
scheduleTask @ zone-evergreen.js:389
scheduleTask @ zone-evergreen.js:211
scheduleMicroTask @ zone-evergreen.js:231
scheduleResolveOrReject @ zone-evergreen.js:841
then @ zone-evergreen.js:967
bootstrapModule @ core.js:42232
./src/main.ts @ main.ts:11
__webpack_require__ @ bootstrap:79
0 @ main.ts:12
__webpack_require__ @ bootstrap:79
checkDeferredModules @ bootstrap:45
webpackJsonpCallback @ bootstrap:32
(anonymous) @ main.js:1
Show 53 more frames
zone-evergreen.js:2828 GET https://localhost:3443/images/ net::ERR_FAILED
scheduleTask @ zone-evergreen.js:2828
scheduleTask @ zone-evergreen.js:386
onScheduleTask @ zone-evergreen.js:273
scheduleTask @ zone-evergreen.js:379
scheduleTask @ zone-evergreen.js:211
scheduleMacroTask @ zone-evergreen.js:234
scheduleMacroTaskWithCurrentZone @ zone-evergreen.js:1118
(anonymous) @ zone-evergreen.js:2861
proto.<computed> @ zone-evergreen.js:1433
(anonymous) @ http.js:2615
_trySubscribe @ Observable.js:42
subscribe @ Observable.js:28
subscribeToResult @ subscribeToResult.js:9
_innerSub @ mergeMap.js:59
_tryNext @ mergeMap.js:53
_next @ mergeMap.js:36
next @ Subscriber.js:49
(anonymous) @ subscribeToArray.js:3
_trySubscribe @ Observable.js:42
subscribe @ Observable.js:28
call @ mergeMap.js:21
subscribe @ Observable.js:23
call @ filter.js:13
subscribe @ Observable.js:23
call @ map.js:16
subscribe @ Observable.js:23
call @ catchError.js:16
subscribe @ Observable.js:23
ngOnInit @ header.component.ts:41
callHook @ core.js:3937
callHooks @ core.js:3901
executeInitAndCheckHooks @ core.js:3842
refreshView @ core.js:11795
refreshComponent @ core.js:13217
refreshChildComponents @ core.js:11508
refreshView @ core.js:11829
renderComponentOrTemplate @ core.js:11903
tickRootContext @ core.js:13379
detectChangesInRootView @ core.js:13413
detectChanges @ core.js:15093
tick @ core.js:42683
_loadComponent @ core.js:42733
bootstrap @ core.js:42659
(anonymous) @ core.js:42251
_moduleDoBootstrap @ core.js:42247
(anonymous) @ core.js:42202
invoke @ zone-evergreen.js:365
onInvoke @ core.js:41257
invoke @ zone-evergreen.js:364
run @ zone-evergreen.js:124
(anonymous) @ zone-evergreen.js:851
invokeTask @ zone-evergreen.js:400
onInvokeTask @ core.js:41235
invokeTask @ zone-evergreen.js:399
runTask @ zone-evergreen.js:168
drainMicroTaskQueue @ zone-evergreen.js:570
Promise.then (async)
scheduleMicroTask @ zone-evergreen.js:553
scheduleTask @ zone-evergreen.js:389
scheduleTask @ zone-evergreen.js:211
scheduleMicroTask @ zone-evergreen.js:231
scheduleResolveOrReject @ zone-evergreen.js:841
then @ zone-evergreen.js:967
bootstrapModule @ core.js:42232
./src/main.ts @ main.ts:11
__webpack_require__ @ bootstrap:79
0 @ main.ts:12
__webpack_require__ @ bootstrap:79
checkDeferredModules @ bootstrap:45
webpackJsonpCallback @ bootstrap:32
(anonymous) @ main.js:1
Show 26 more frames
home:1 Access to XMLHttpRequest at 'https://localhost:3443/images/' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
core.js:5873 ERROR TypeError: Cannot read property 'filename' of undefined
    at HomeComponent_Template (home.component.html:3)
    at executeTemplate (core.js:11930)
    at refreshView (core.js:11777)
    at refreshComponent (core.js:13217)
    at refreshChildComponents (core.js:11508)
    at refreshView (core.js:11829)
    at refreshDynamicEmbeddedViews (core.js:13142)
    at refreshView (core.js:11800)
    at refreshComponent (core.js:13217)
    at refreshChildComponents (core.js:11508)
defaultErrorLogger @ core.js:5873
handleError @ core.js:5926
(anonymous) @ core.js:42696
invoke @ zone-evergreen.js:365
run @ zone-evergreen.js:124
runOutsideAngular @ core.js:41093
tick @ core.js:42693
(anonymous) @ core.js:42533
invoke @ zone-evergreen.js:365
onInvoke @ core.js:41257
invoke @ zone-evergreen.js:364
run @ zone-evergreen.js:124
run @ core.js:41032
next @ core.js:42530
schedulerFn @ core.js:36857
__tryOrUnsub @ Subscriber.js:183
next @ Subscriber.js:122
_next @ Subscriber.js:72
next @ Subscriber.js:49
next @ Subject.js:39
emit @ core.js:36819
checkStable @ core.js:41171
onLeave @ core.js:41332
onInvokeTask @ core.js:41241
invokeTask @ zone-evergreen.js:399
runTask @ zone-evergreen.js:168
invokeTask @ zone-evergreen.js:481
invokeTask @ zone-evergreen.js:1596
globalZoneAwareCallback @ zone-evergreen.js:1622
error (async)
customScheduleGlobal @ zone-evergreen.js:1735
scheduleTask @ zone-evergreen.js:386
onScheduleTask @ zone-evergreen.js:273
scheduleTask @ zone-evergreen.js:379
scheduleTask @ zone-evergreen.js:211
scheduleEventTask @ zone-evergreen.js:237
(anonymous) @ zone-evergreen.js:1907
(anonymous) @ http.js:2604
_trySubscribe @ Observable.js:42
subscribe @ Observable.js:28
subscribeToResult @ subscribeToResult.js:9
_innerSub @ mergeMap.js:59
_tryNext @ mergeMap.js:53
_next @ mergeMap.js:36
next @ Subscriber.js:49
(anonymous) @ subscribeToArray.js:3
_trySubscribe @ Observable.js:42
subscribe @ Observable.js:28
call @ mergeMap.js:21
subscribe @ Observable.js:23
call @ filter.js:13
subscribe @ Observable.js:23
call @ map.js:16
subscribe @ Observable.js:23
call @ catchError.js:16
subscribe @ Observable.js:23
ngOnInit @ home.component.ts:21
callHook @ core.js:3937
callHooks @ core.js:3901
executeInitAndCheckHooks @ core.js:3842
refreshView @ core.js:11795
refreshDynamicEmbeddedViews @ core.js:13142
refreshView @ core.js:11800
refreshComponent @ core.js:13217
refreshChildComponents @ core.js:11508
refreshView @ core.js:11829
renderComponentOrTemplate @ core.js:11903
tickRootContext @ core.js:13379
detectChangesInRootView @ core.js:13413
detectChanges @ core.js:15093
tick @ core.js:42683
(anonymous) @ core.js:42533
invoke @ zone-evergreen.js:365
onInvoke @ core.js:41257
invoke @ zone-evergreen.js:364
run @ zone-evergreen.js:124
run @ core.js:41032
next @ core.js:42530
schedulerFn @ core.js:36857
__tryOrUnsub @ Subscriber.js:183
next @ Subscriber.js:122
_next @ Subscriber.js:72
next @ Subscriber.js:49
next @ Subject.js:39
emit @ core.js:36819
checkStable @ core.js:41171
onHasTask @ core.js:41278
hasTask @ zone-evergreen.js:420
_updateTaskCount @ zone-evergreen.js:441
_updateTaskCount @ zone-evergreen.js:264
runTask @ zone-evergreen.js:185
drainMicroTaskQueue @ zone-evergreen.js:570
Promise.then (async)
scheduleMicroTask @ zone-evergreen.js:553
scheduleTask @ zone-evergreen.js:389
scheduleTask @ zone-evergreen.js:211
scheduleMicroTask @ zone-evergreen.js:231
scheduleResolveOrReject @ zone-evergreen.js:841
then @ zone-evergreen.js:967
bootstrapModule @ core.js:42232
./src/main.ts @ main.ts:11
__webpack_require__ @ bootstrap:79
0 @ main.ts:12
__webpack_require__ @ bootstrap:79
checkDeferredModules @ bootstrap:45
webpackJsonpCallback @ bootstrap:32
(anonymous) @ main.js:1
Show 61 more frames
zone-evergreen.js:2828 GET https://localhost:3443/images/ net::ERR_FAILED

1 Ответ

1 голос
/ 09 апреля 2020

Похоже, вам нужно использовать оператор forkJoin RxJs для объединения этих двух observables в одну подписку, если наблюдаемые не связаны друг с другом, и вас интересуют только окончательные результаты обоих из них

проверьте документацию для получения дополнительной информации forkJoin

Это что-то вроде Promise.all (), если вы знакомы с обещаниями

, поэтому компонент заголовка ngOnInit может

ngOnInit() {

  let userObs = this.authService.getUsername(); // the user observable
  let imagesObs = this.imageService.getImages(); // the images observable

  this.subscription = forkJoin([userObs, imagesObs]).subscribe(results => {
    // results[0] is the user
    // results[1] is the images
    this.username = results[0];

    let images = results[1];
    this.logo_image = images.find(image => image.destination == 'logo.png');
  });
}

не забудьте также импортировать forkJoin из rxjs

, убедитесь, что результаты возвращаются с сервера так, как вам нужно, может быть, с сервера нет изображений

...