使用Angular获取MongoDB中存储的Posts时出现404(Not Found)错误求助
Hey, I see the issue right away—you're hitting a 404 because your frontend is sending a GET request to /posts, but your backend has only configured a POST route for that path. Let's fix this step by step:
1. Fix the Backend Route Method
Your current backend code uses router.post for /posts, which tells Express to only handle POST requests at that path. Since your Angular app is making a GET request, Express doesn't recognize the route and returns a 404. Update the route to use router.get instead:
// Replace this router.post('/posts', getAllPosts); // With this router.get('/posts', getAllPosts);
2. Confirm Your Backend Handler is Working
Great news—your getAllPosts function logic is correct. It properly queries all documents from the post collection, returns a 200 status with the data on success, and a 400 status with the error on failure. No changes needed here!
3. Quick Additional Checks
To cover all bases, make sure:
- Your backend server is actually running on port 8000 (double-check your server startup code to confirm the port number).
- If your Angular app runs on a different port (like the default 4200), you've set up CORS on your backend (using the
corsnpm package, for example) to avoid cross-origin errors once the 404 is fixed. - Your
postMongoose model is properly defined and connected to the correct MongoDB collection.
Once you update the route method, your displayPosts() function should successfully fetch the posts data without the 404 error.
内容的提问来源于stack exchange,提问作者Anthony Andrews

