当前位置: 首页 > 知识库问答 >
问题:

当我试图从数据库中获取信息时,出现了一个错误

潘翰藻
2023-03-14

我有一个angular应用程序,它有一个带有客舱的页面,当你点击一个客舱时,它应该会带你到客舱详细信息页面。当我用json-server数据库进行测试时,这工作得很好,但是当我创建并将其连接到我的express服务器时,当我试图导航到我的cabindetail页面时,出现了一个错误。

我是新的角度和节点,所以我有点迷失了。

这就是错误。

错误 错误:未捕获(在promise中):错误:无法匹配任何路由。网址细分:“客舱详细信息”错误:无法匹配任何路线。URL 段:ApplyRedirects.push上的“cabindetail”。/node_modules/@angular/router/fesm5/router.js.ApplyRedirects.noMatchError (router.js:2469) at CatchSubscriber.selector (router.js:2450) at CatchSubscriber.push../node_modules/rxjs/_esm5/internal/operators /catchError.js.CatchSubscriber.error (catchError.js:34) at MapSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._error (Subscriber.js:79) at MapSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.error (Subscriber.js:59) at MapSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._error (Subscriber.js:79) at MapSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.error (Subscriber.js:59) at MapSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._error (Subscriber.js:79) at MapSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.error (Subscriber.js:59) at TapSubscriber.push../node_modules/rxjs/_esm5/internal/operators /tap.js.TapSubscriber._error (tap.js:61) at resolvePromise (zone.js:831) at resolvePromise (zone.js:788) at zone.js:892 at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:423) at Object.onInvokeTask (core.js:17290) at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:422) at Zone.push../node_modules/zone.js/dist/zone.js.Zone.runTask (zone.js:195) at drainMicroTaskQueue (zone.js:601) at ZoneTask.push../node_modules/zone.js/dist/zone.js.ZoneTask.invokeTask [as invoke] (zone.js:502) at invokeTask (zone.js:1744) defaultErrorLogger @ core.js:15724

这是我的cabinRouter.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 {}

这些是指向我的完整项目的位桶链接。角

https://bit bucket . 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}`);
  }

}

我的机舱细节组件

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: ''
    });
  }


}

共有1个答案

苍温文
2023-03-14

如我所见,Angular抛出了一个路由器错误,即cabindetail在路由表中找不到。

当我检查您提供的代码时,我发现路由表需要一个参数:路由中的id,所以当您连接到JSON服务器时(数据非常好,模型中的Id被填充,例如路由出现为cabindetail/5。

似乎发生了什么,当您连接您的express服务器时,id属性没有被填充到模型中,这使得route /cabindetail/根据路由表它是无效的(因为id将是未定义的并且不是0)。

您需要做的是检查来自服务器的JSON并确保ID已正确填充。

 类似资料:
  • 失败:生成失败,出现异常。 > 执行时发生故障com.android.build.gradle.internal.tasks.工人$ActionFacade Android资源链接失败 /Users/macos/Documents/SubmissionExpert1/app/src/main/res/layout/data.xml:12: AAPT:错误:资源字符串/name_heroes(又名c

  • DBMetas() xorm支持获取表结构信息,通过调用 engine.DBMetas() 可以获取到数据库中所有的表,字段,索引的信息。 TableInfo() 根据传入的结构体指针及其对应的Tag,提取出模型对应的表结构信息。这里不是数据库当前的表结构信息,而是我们通过struct建模时希望数据库的表的结构信息

  • 我有一个供应商列表,当我点击其中一个时,它会打开一个更详细的页面,包含URL、专业化、国家等信息。 最近,我一直试图打开供应商的详细页面,但每次我尝试这样做,我的应用程序崩溃,我得到以下错误消息: 错误指出了以下代码: 如果有人知道为什么会发生这种情况,或者我可以在代码中查找什么,那将是一个很大的帮助(:

  • 我正在创建一个JavaFX应用程序,我已经很好地连接到了数据库。然而,当我从表中获取数据时,我得到了一个错误 组织。h2.jdbc。JdbcSQLException:未找到表“touch”;SQL语句:从讲座[42102-192]中选择名称 我100%确定我连接到数据库并且表肯定在那里,对为什么会这样有任何建议吗? hear是我的连接代码和我正在运行的代码,以便您可以看到 和正在运行的查询

  • 我试图从使用vba的SQL查询中获取一些数据,但当我尝试运行代码时,它会给我一个类型不匹配错误。有人能帮忙吗

  • 我试图使用Bean shell断言从我的JBDC请求采样器中提取结果 我在我的采样器中添加了一个beanshell断言来提取结果,但运行时出现了一个错误。有关守则是: 其中dataFromDB是我的JBDC请求采样器的结果变量名 错误是:断言失败消息:org。阿帕奇。乔芬。util。JMeterException:调用bsh方法时出错:eval