【问题标题】:How to solve DELETE error 404 not found express.js如何解决 DELETE 错误 404 not found express.js
【发布时间】:2020-04-06 01:50:12
【问题描述】:

我正在学习 MEAN Stack 课程。我可以成功添加新数据和 fetch 数据,但是当我尝试删除数据时,问题就出现了。错误是说 “DELETE http://localhost:3200/posts/5e831685bf7c02d96057db9e 404 (Not Found)”。我将在下面提供所有代码文件文件,请有人帮助我。


错误截图


我在这个项目上使用, Angular, node.js | express.js, mongoDB |猫鼬棱角材质


如果需要项目链接在这里:https://drive.google.com/drive/folders/1lAsQuQNfgxJFBR1SgcetEdEbakxzSm5s?usp=sharing


app.js 文件

const express = require("express");
const bodyParser = require("body-parser");
const Post = require("./models/post");
const mongoose = require("mongoose");
const cors  = require("cors");

const app = express();

mongoose.connect("mongodb+srv://zee:S6I6sf4vX3X47arn@cluster0-5cydp.mongodb.net/node-angular?retryWrites=true&w=majority")
.then(() => {
  console.log('Connected to the Database');
})
.catch(() => {
  console.log('Connection failed!');
});

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));

app.use(cors());

app.use((req, res, next) => {
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept"
    );
  res.setHeader(
    "Access-Control-Allow-Methods",
    "GET, POST, PATCH, DELETE, OPTIONS"
    );
  next();
});


app.post('/api/posts',(req, res, next) => {
  const post = new Post({
    title: req.body.title,
    content: req.body.content
  });
  post.save();
  res.status(201).json({
  message: 'Post added Succesfuly'
  });
});

app.get('/api/posts',(req, res, next) => {
  Post.find().then(documents => {
    res.status(200).json({
      message: 'Posts Succesfuly!',
      posts: documents
    });
  });
 });

app.delete('/app/posts/:id', (req, res, next) => {
  Post.deleteOne({_id: req.params.id}).then(result => {
    console.log(result);
    res.status(200).json({message: 'Post deleted!'});
  });
});

// app.delete((req, res, next) => {
//   console.log(req.params.id);
//   res.status(200).json({message: 'Post deleted!'});
// });

module.exports = app;

post.service.ts | API请求文件

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Subject } from 'rxjs';
import { map } from 'rxjs/operators';


import { Post } from './post.model';

@Injectable({ providedIn: 'root' })
export class PostsService {
  private posts: Post[] = [];
  private postsUpdated = new Subject<Post[]>();

  constructor(private http: HttpClient) {}

  getPosts() {
    this.http
      .get<{ message: string; posts: any }>(
        'http://localhost:3200/api/posts'
      )
      .pipe(map((postData) => {
        return postData.posts.map(post => {
          return {
            title: post.title,
            content: post.content,
            id: post._id
          };
        });
      }))
      .subscribe(transformPosts => {
        this.posts = transformPosts;
        this.postsUpdated.next([...this.posts]);
      });
  }

  getPostUpdateListener() {
    return this.postsUpdated.asObservable();
  }

  addPost(title: string, content: string) {
    // tslint:disable-next-line: object-literal-shorthand
    const post: Post = { id: null, title: title, content: content };
    this.http
      .post<{ message: string }>('http://localhost:3200/api/posts', post)
      .subscribe((responseData) => {
        console.log(responseData.message);
        this.posts.push(post);
        this.postsUpdated.next([...this.posts]);
      });
  }
  deletePost(postId: string){
    this.http.delete('http://localhost:3200/posts/' + postId)
    .subscribe(() => {
      console.log('Deleted!');
    });
  }
}

HTML 文件 | (post-list.component.html)

<mat-accordion multi="true" *ngIf="posts.length > 0">
  <mat-expansion-panel *ngFor="let post of posts">
    <mat-expansion-panel-header>
      {{post.title}}
    </mat-expansion-panel-header>
    <p>{{post.content}}</p>
    <mat-action-row>
      <button mat-button color="primary" >EDIT</button>
      <button mat-button color="warn" (click)="onDelete(post.id)" >DELETE</button>
    </mat-action-row>
  </mat-expansion-panel>
</mat-accordion>
<p class="mat-body-1 info-text" *ngIf="posts.length <=0">No post added yet!</p>

类型脚本文件 | (post-list.component.ts)

import { Component, OnInit, OnDestroy } from '@angular/core';

import { Post } from '../post.model';
import { Subscription } from 'rxjs';
import { PostsService } from '../posts.service';

@Component({
  selector: 'app-post-list',
  templateUrl: './post-list.component.html',
  styleUrls: ['./post-list.component.css'],
})

export class PostListComponent implements OnInit, OnDestroy{
// posts = [
//   {title: 'First Post', content: 'This is the first post\'\s content'},
//   {title: 'Second Post', content: 'This is the second post\'\s content'},
//   {title: 'Third Post', content: 'This is the third post\'\s content'},
// ];
posts: Post[] = [];
  private postsSub: Subscription;

  constructor(public postsService: PostsService){}

  ngOnInit() {
    this.postsService.getPosts();
    this.postsSub = this.postsService.getPostUpdateListener()
      .subscribe((posts: Post[]) => {
        this.posts = posts;
      });
  }

  onDelete(postId: string){
    this.postsService.deletePost(postId);
  }

  ngOnDestroy() {
    this.postsSub.unsubscribe();
  }

}

【问题讨论】:

  • 可能只是路由 app.delete('/app/posts/:id 中的拼写错误。其他路线跟随/api/...。需要在调用删除路由的 Angular 代码中进行调整。
  • 你的DELETE 路由是/app/posts/:id,而不是/api/...

标签: javascript node.js angular mongodb express


【解决方案1】:

您的代码中有一个小错误。您的delete 路线是/app/posts/:id,但在您的角度应用程序中,您调用的是/posts/:id

试试这个。

 deletePost(postId: string){
    this.http.delete('http://localhost:3200/app/posts/' + postId)
    .subscribe(() => {
      console.log('Deleted!');
    });
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-20
    • 1970-01-01
    • 2016-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-04
    • 2012-01-29
    相关资源
    最近更新 更多