I am trying to fetch Posts saved in Mongodb using Angular.
GET http://localhost:8000/posts 404 (Not Found)
ERROR: HttpErrorResponse {headers: HttpHeaders, status: 404, statusText: 'Not Found', url: 'http://localhost:8000/posts', ok: false, …}
Please find my code below:
API for fetching Posts:
getAllPosts(){
return this.http.get('http://localhost:8000/posts');
}
Actual Method for fetching Posts:
displayPosts(){
this.getAllPosts()
.subscribe((item)=>{
this.responseData = item;
})
}
Backend Route:
router.post('/posts', getAllPosts);
Method for backend fetching Posts:
const getAllPosts = async(request,response)=>{
try{
const posts = await post.find({});
return response.status(200).json(posts);
}
catch(err){
return response.status(400).json(err);
}
}
I am trying to fetch the posts.
CodePudding user response:
When you write
router.post('/posts', getAllPosts);
You can get your posts only with POST method.
Either use
return this.http.post('http://localhost:8000/posts');
on the clientside. Or change backend method to
router.get('/posts', getAllPosts);