You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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 cors npm package, for example) to avoid cross-origin errors once the 404 is fixed.
  • Your post Mongoose 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 13:19:07