node.js - 尝试从数据库中获取信息时出现错误
问题描述
我有一个有角度的应用程序,它有一个带有小屋的页面,当您单击小屋时,它应该带您进入小屋详细信息页面。当我使用 json-server 数据库进行测试时,这可以正常工作,但是当我创建它并将其连接到我的快速服务器时,我在尝试导航到我的小屋详细信息页面时遇到错误。
我是 angular 和 nodejs 的新手,所以我对此有点迷茫。
这是错误。
ERROR 错误:未捕获(在承诺中):错误:无法匹配任何路由。URL 段:'cabindetail' 错误:无法匹配任何路由。URL 段:在 ApplyRedirects.push../node_modules/@angular/router/fesm5/router.js.ApplyRedirects.noMatchError (router.js:2469) 在 CatchSubscriber.selector (router.js:2450) 在 CatchSubscriber 的“cabindetail”。 push../node_modules/rxjs/_esm5/internal/operators/catchError.js.CatchSubscriber.error (catchError.js:34) 在 MapSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._error (Subscriber.js:79) 在 MapSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.error (Subscriber.js:59) 在 MapSubscriber.push../node_modules/rxjs/_esm5/internal /Subscriber.js.Subscriber._error (Subscriber.js:79) 在 MapSubscriber.push..
这是我的cabineRouter.js
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const authenticate = require('../authenticate');
const cors = require('./cors');
const Cabins = require('../models/cabins');
const cabinRouter = express.Router();
cabinRouter.use(bodyParser.json());
cabinRouter.route('/')
.options(cors.corsWithOptions, (req,res) => {res.sendStatus(200); })
.get(cors.cors, (req, res, next) => {
Cabins.find(req.query)
.populate('comments.author')
.then((cabin) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.json(cabin);
}, (err) => next(err))
.catch((err) => next(err));
})
.post(cors.corsWithOptions, /*authenticate.verifyUser, authenticate.verifyAdmin,*/ (req, res, next) => {
Cabins.create(req.body)
.then((cabin) => {
console.log('Cabin Created', cabin);
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.json(cabin);
}, (err) => next(err))
.catch((err) => next(err));
})
.put(cors.corsWithOptions, authenticate.verifyUser,authenticate.verifyAdmin, (req, res, next) => {
res.statusCode = 403;
res.end('PUT operation not supported on /cabins');
})
.delete(cors.corsWithOptions, /*authenticate.verifyUser, authenticate.verifyAdmin,*/ (req, res, next) => {
Cabins.remove({})
.then((resp) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.json(resp);
}, (err) => next(err))
.catch((err) => next(err));
});
cabinRouter.route('/:cabinId')
.options(cors.corsWithOptions, (req,res) => {res.sendStatus(200); })
.get(cors.cors, (req, res, next) => {
Cabins.findById(req.params.cabinId)
.populate('comments.author')
.then((cabin) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.json(cabin);
}, (err) => next(err))
.catch((err) => next(err));
})
.post(cors.corsWithOptions,/*authenticate.verifyUser, authenticate.verifyAdmin,*/ (req, res, next) => {
res.statusCode = 403;
res.end('POST operation not supported on /cabins/' + req.params.cabinId);
})
.put(cors.corsWithOptions, /*authenticate.verifyUser, authenticate.verifyAdmin,*/ (req, res, next) => {
Cabins.findByIdAndUpdate(req.params.cabinId, {
$set: req.body
}, {new: true})
.then((cabin) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.json(cabin);
}, (err) => next(err))
.catch((err) => next(err));
})
.delete(cors.corsWithOptions, /*authenticate.verifyUser, authenticate.verifyAdmin,*/ (req, res, next) => {
Cabins.findByIdAndRemove(req.params.cabinId)
.then((resp) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.json(resp);
}, (err) => next(err))
.catch((err) => next(err));
});
module.exports = cabinRouter;
这是我的 app-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from '../home/home.component';
import { CabinsComponent } from '../cabins/cabins.component';
import { HousesComponent } from '../houses/houses.component';
import { EcoactivitiesComponent } from '../ecoactivities/ecoactivities.component';
import { ContactComponent } from '../contact/contact.component';
import { CabinDetailComponent } from '../cabin-detail/cabin-detail.component';
import { HouseDetailComponent } from '../house-detail/house-detail.component';
const routes: Routes = [
{ path: '', redirectTo: '/home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent },
{ path: 'cabin', component: CabinsComponent },
{ path: 'house', component: HousesComponent },
{ path: 'cabindetail/:id', component: CabinDetailComponent },
{ path: 'housedetail/:id', component: HouseDetailComponent },
{ path: 'ecoactivity', component: EcoactivitiesComponent },
{ path: 'contact', component: ContactComponent },
];
@NgModule({
imports: [ RouterModule.forRoot(routes) ],
exports: [ RouterModule ]
})
export class AppRoutingModule {}
这些是我完整项目的 bitbucket 链接。角
https://bitbucket.org/natashanodine/vilcabambahotel-angular/src/master/
节点快递服务器
https://bitbucket.org/natashanodine/vilcabamba-hotel-server/src/master/
这是我的客舱服务
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { catchError, map, tap, flatMap } from 'rxjs/operators';
import { Cabin } from '../shared/cabin';
import { Comment } from '../shared/comment';
import { MessageService } from './message.service';
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
@Injectable({
providedIn: 'root'
})
export class CabinService {
private cabinsUrl = 'http://localhost:3000/cabins'; // URL to web api
constructor(
private http: HttpClient,
private messageService: MessageService) { }
/** GET cabins from the server */
getCabins(): Observable<Cabin[]> {
return this.http.get<Cabin[]>(this.cabinsUrl)
.pipe(
tap(cabins => this.log('fetched cabins')),
catchError(this.handleError('getCabins', []))
);
}
getFeaturedCabin(): Observable<Cabin[]> {
const url = 'http://localhost:3000/cabins?featured=true';
return this.http.get<Cabin[]>(url).pipe(
tap(_ => this.log('o')),
catchError(this.handleError<Cabin[]>(`getFeaturedCabin`))
);
}
/** GET cabin by id. Return `undefined` when id not found */
getCabinNo404<Data>(id: string): Observable<Cabin> {
const url = `${this.cabinsUrl}/?id=${id}`;
return this.http.get<Cabin[]>(url)
.pipe(
map(cabins => cabins[0]), // returns a {0|1} element array
tap(h => {
const outcome = h ? `fetched` : `did not find`;
this.log(`${outcome} cabin id=${id}`);
}),
catchError(this.handleError<Cabin>(`getCabin id=${id}`))
);
}
/** GET cabin by id. Will 404 if id not found */
getCabin(id: string): Observable<Cabin> {
const url = `${this.cabinsUrl}/${id}`;
return this.http.get<Cabin>(url).pipe(
tap(_ => this.log(`fetched cabin id=${id}`)),
catchError(this.handleError<Cabin>(`getCabin id=${id}`))
);
}
updatePosts(id, newcomment) {
const comment: Comment = newcomment;
return this.http.get<Cabin>('http://localhost:3000/cabins/' + id).pipe(
map(cabin => {
return {
id: cabin._id,
name: cabin.name,
image: cabin.image,
description: cabin.description,
priceweek: cabin.priceweek,
pricemonth: cabin.pricemonth,
featured: cabin.featured,
comments: cabin.comments
};
}),
flatMap((updatedCabin) => {
updatedCabin.comments.push(comment);
return this.http.put(this.cabinsUrl + '/' + id, updatedCabin);
})
);
}
/**
* Handle Http operation that failed.
* Let the app continue.
* @param operation - name of the operation that failed
* @param result - optional value to return as the observable result
*/
private handleError<T>(operation = 'operation', result?: T) {
return (error: any): Observable<T> => {
// TODO: send the error to remote logging infrastructure
console.error(error); // log to console instead
// TODO: better job of transforming error for user consumption
this.log(`${operation} failed: ${error.message}`);
// Let the app keep running by returning an empty result.
return of(result as T);
};
}
/** Log a CabinService message with the MessageService */
private log(message: string) {
this.messageService.add(`CabinService: ${message}`);
}
}
我的小屋细节.component
import { Location } from '@angular/common';
import { Component, Inject, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Params, ActivatedRoute } from '@angular/router';
import { Comment } from '../shared/comment';
import { Cabin } from '../shared/cabin';
import { CabinService } from '../services/cabin.service';
@Component({
selector: 'app-cabin-detail',
templateUrl: './cabin-detail.component.html',
styleUrls: ['./cabin-detail.component.css']
})
export class CabinDetailComponent implements OnInit {
cabin: Cabin;
cabins: Cabin[];
comment: Comment;
commentForm: FormGroup;
errMess: string;
formErrors = {
'author' : '',
'rating' : '',
'comment' : ''
};
validationMessages = {
'author' : {
'required' : 'Name is required',
'minlength' : 'Name must be at least 2 characters long',
'maxlength' : 'Name cannot be more that 25 characters long'
}
};
constructor(
private cabinService: CabinService,
private fb: FormBuilder,
private location: Location,
private route: ActivatedRoute,
@Inject("BaseURL") private BaseURL
) {
this.createForm();
}
ngOnInit(): void {
this.getCabin();
this.getCabins();
}
getCabin(): void {
const id = +this.route.snapshot.paramMap.get('id');
this.cabinService.getCabin(id)
.subscribe(cabin => this.cabin = cabin);
}
getCabins(): void {
this.cabinService.getCabins()
.subscribe(cabins => this.cabins = cabins);
}
/* addComment(description: string): void {
description = description.trim();
if (!description) { return; }
this.cabinService.addCabin({ description } as Cabin)
.subscribe(cabin => {
this.cabins.push(cabin);
});
}
*/
/* delete(cabin: Cabin): void {
this.cabins = this.cabins.filter(h => h !== cabin);
this.cabinService.deleteCabin(cabin).subscribe();
}
*/
createForm() {
this.commentForm = this.fb.group({
author: ['', [ Validators.required, Validators.minLength(2) ] ],
rating: 5,
comment: ['', [ Validators.required ] ],
});
this.commentForm.valueChanges
.subscribe(data => this.onValueChanged(data));
this.onValueChanged(); // (re)set form validation messages
}
onValueChanged(commentFormData?: any) {
if (!this.commentForm) {
return;
}
const form = this.commentForm;
for (const field in this.formErrors) {
this.formErrors[field] = '';
const control = form.get(field);
if (control && control.dirty && !control.valid) {
const messages = this.validationMessages[field];
for (const key in control.errors) {
this.formErrors[field] += messages[key] + ' ';
}
}
}
if (this.commentForm.valid) {
this.comment = this.commentForm.value;
} else {
this.comment = undefined;
}
}
onSubmit() {
const id = +this.route.snapshot.paramMap.get('id');
this.comment['date'] = new Date().toISOString();
this.cabin.comments.push(this.comment);
this.cabinService.updatePosts(this.cabin._id, this.comment).subscribe(() => {
console.log("PUT is done");
})
this.commentForm.reset({
author: '',
rating: 5,
comment: ''
});
}
}
解决方案
正如我所看到的,Angular 抛出了一个路由器错误,在路由表中找不到该cabinedetail。
当我检查您提供的代码时,我发现路由器表需要一个参数 :id 在路由中,所以当您连接到 JSON 服务器时(并且数据非常好,模型中的 Id 被填充并且例如,路线以cabinedetail/5 的形式出现。
似乎发生了什么,当您连接快递服务器时,模型中没有填充 id 属性,这使得路由 /cabindetail/ 并且根据路由表它是无效的(因为 Id 将是未定义的而不是0)。
您需要做的是检查来自服务器的 JSON 并确保正确填充了 Id。
推荐阅读
- next.js - nextjs 安装的组件没有获取数据
- laravel - 如何防止 laravel mix 编译
- hibernate - 如何在春季启动数据jpa中的@Entity之间链接外键
- powershell - 列出 CPU 和 GPU 温度的 PowerShell 脚本
- c# - TokenResponse.Properties - OAuth2 身份验证机器人框架
- javascript - 如何强制用户在访问网页之前输入密码?
- python-3.x - 如何将 PDB XML 读取转换为 Pandas Dataframe?
- go - 一种不使用最新的 err 值编写 long defer 的方法?
- ruby-on-rails - 如果它们保存到同一列,如何阻止选择语句覆盖另一个
- python - 如何根据另一个索引矩阵替换矩阵的元素?