Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
32
rated 0 times [  33] [ 1]  / answers: 1 / hits: 5603  / 4 Years ago, mon, april 6, 2020, 12:00:00

I am learning a MEAN Stack course. I can successfully add new data and fletch data but when I trying to DELETE data then the problem is occurring. error is saying DELETE http://localhost:3200/posts/5e831685bf7c02d96057db9e 404 (Not Found). I'll provide below all the code file files please someone help me on this.






Error screenshot



enter






I'm using on this project,
Angular, node.js | express.js, mongoDB | mongoose, angular material






if need project link here: https://drive.google.com/drive/folders/1lAsQuQNfgxJFBR1SgcetEdEbakxzSm5s?usp=sharing






app.js File



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:[email protected]/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 request File



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 File | (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>


typeScricpt File | (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();
}

}

More From » node.js

 Answers
5

You have a small mistake in your code. your delete route is /app/posts/:id, but in you angular app you are calling /posts/:id.



Try this.



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

[#4255] Friday, April 3, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
zaynerogerb

Total Points: 454
Total Questions: 109
Total Answers: 97

Location: Comoros
Member since Tue, Mar 14, 2023
1 Year ago
zaynerogerb questions
;