问题
I am trying to store some images on my Node.JS server and read it from Angular client with the following codes:
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));
}
}
models/image.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;
And the 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));
})
I can upload images successfully using Postman, and I get the result like following:
{
"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
}
And it will be stored in MongoDB like this:
{
"_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
}
But I don't know what is the problem that I can's see the images on my website and get these error messages:
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:
it seems you need to use forkJoin RxJs
operator to combine these two observables
into one subscription, as long as the observables are not related to each other, and you are interested only in the final results of both of them
check the documentation for more info forkJoin
it's something like Promise.all() if you are familiar with promises
so the header component ngOnInit may look something like that
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');
});
}
do not forget to import forkJoin
from rxjs
also, make sure that the results are coming back from the server as you needed exactly, maybe there is no images back from the server
来源:https://stackoverflow.com/questions/61119340/core-js5873-error-typeerror-cannot-read-property-filename-of-undefined