Error status: 404 returned with PUT request using Node.js (express), Angular, and MongoDB

Viewed 504

I'm really stuck trying to figure out how to update my data("Post") to MongoDB (I'm using Mongoose, MongoDB, Node, Express, and Angular 9.1.1). I have no trouble with POST and DELETE, but can't figure out where I'm going wrong with PUT.

Thanks in advance, all help really appreciated -Geoff

ANGULAR: file post.ts

export class Post {
    id: string;
    title: string;
    message: string;
 }

ANGULAR: file postsService.ts

//Working OK
deletePost(postId: string) {
    this.http.delete(`http://localhost:3000/api/posts/${postId}`)
        .subscribe(() => {
            const updatedPosts = this.posts.filter(post => post.id !== postId);
            this.posts = updatedPosts;
            this.postsUpdate$.next([...this.posts]);
        });
    }

//Not working - I want to update one post
updatePost(postId: string, postTitle: string, postMessage: string) {
    const post: Post = { id: postId, title: postTitle, message: postMessage };
    this.http.put(`http://localhost:3000/api/posts/${postId}`, post)
        .subscribe(response => console.log(response));
    }

NODE SERVER: File backend/app.js

// Working OK
app.delete("/api/posts/:id", (req, res, next) => {
    Post.deleteOne({ _id: req.params.id }).then((result) => {
        console.log(req.params.id);
        res.status(200).json({ msg: "Post deleted successfully!" });
    });
});

//Not working - I want to update one post
// Post is defined in file: backend/model/post.js
app.put("/api/post/:id", (req, res, next) => {
    const post1 = new Post({
        _id: req.body.id,
        title: req.body.title,
        message: req.body.message,
    });
Post.findOneAndUpdate({ _id: req.params.id } ,post1)
    .then((result) => {
    console.log(result);
    res.status(200).json({ msg: "Updated successfully!" });
    });
});

NODE: backend/model/post.js

const mongoose = require("mongoose");

//note "String is a class used in node/mongoDB"
const postSchema = mongoose.Schema({
    title: { type: String, required: true },
    message: { type: String, required: true },
});
// this will automaticly be stored in collection "posts"
module.exports = mongoose.model('Post', postSchema);

ERROR IN BROWSER:

// HEADERS:
Request URL:http://localhost:3000/api/posts/5ef676c71105924a08b9e919
Request Method:PUT
Remote Address:127.0.0.1:3000
Status Code:
404
Version:HTTP/1.1
Referrer Policy:strict-origin-when-cross-origin

// REQUEST:
 
Request Payload:
{"id":"5ef676c71105924a08b9e919", "title":"first Post ", "message":"This is just some text"}

// RESPONCE:
Cannot PUT /api/posts/5ef676c71105924a08b9e919

BUT AT URL ALL IS FINE ON GET:

{"msg":"Post fetched successfully!","posts":{"_id":"5ef676c71105924a08b9e919","title":"first Post ","message":"This is just some text","__v":0}}
2 Answers

Your api put request is targeting the wrong url angular

this.http.put(`http://localhost:3000/api/posts/${postId}`, post)

backend

app.put("/api/post/:id", (req, res, next) => {

one is post the other its posts. they need to be the same.

It seems like you are trying to update one post's Record so you can simply try this

router.put('/api/post/:id', async (req, res, next) => {
    return Post.updateOne({
            _id: req.params.id
        }, {
            $set: {
                title: req.body.title,
                message: req.body.message
            }
        })
        .then(result => res.json(result))
        .catch(err => console.log(err))
});

There is no need to create a new Post because you are trying to update an existing record based on the id and also you are sending routs path like api/post but you are getting a response from the server api/posts so check your route path as well.

Related