Axios GET 请求获取特定用户的推文,返回 500 错误,路由未到达

问题描述 投票:0回答:1

我正在开发 Twitter 克隆,并在为经过身份验证的用户获取推文时遇到问题。尽管有有效的令牌和其他路由正常工作,但 /tweets/user 路由未到达,并且我收到 500 错误。终端中没有显示该路线的日志。

Profile.jsx:

    const fetchUserTweets = async () => {
      console.log(token) //token is printed in browser logs
      try {
        const response = await axios.get(`${API_URL}/tweets/user`, {
          headers: { Authorization: `Bearer ${token}` },
        });
        setUserTweets(response.data);
      } catch (err) {
        console.error('Failed to fetch user tweets', err);
      }
    };

tweet_route.js:

// Get tweets for the authenticated user
router.get('/user', protect, async (req, res) => {
  console.log("Reached /tweets/user route");
  try {
    console.log("reached authenticated user tweets");
    const tweets = await Tweet.find({ tweetedBy: req.user._id })
      .populate('tweetedBy', 'username name profilePic')
      .sort({ date: -1 });
    res.json(tweets);
  } catch (error) {
    console.error('Error fetching tweets for authenticated user:', req.user._id, error);
    res.status(500).json({ message: 'Server error' });
  }
});

.env
文件: VITE_API_URL=http://localhost:5000

Profile.jsx 中的 Axios 请求 URL:

const API_URL = import.meta.env.VITE_API_URL || 'http://localhost:5000';

我知道,

  • 令牌验证有效(记录令牌已验证,用户:)。
  • 我不只是不小心放错了端点
  • 终端中看不到来自 /tweets/user 路由的日志。
  • 其他路由和端点工作正常(例如,获取所有推文、获取用户个人资料、登录、注册)。

我遇到的错误:

Profile.jsx:44 
 
 GET http://localhost:5000/tweets/user 500 (Internal Server Error)

Failed to fetch user tweets AxiosError {message: 'Request failed with status code 500', name: 'AxiosError', code: 'ERR_BAD_RESPONSE', config: {…}, request: XMLHttpRequest, …}

什么可能导致无法到达 /tweets/user 路由,从而导致 500 错误?

谢谢!

reactjs node.js express axios
1个回答
0
投票

/tweets/用户路线未到达...:...该路线没有日志 出现在终端中......

Ans: 请求找到了路由 - router.get('/user', protected, async (req, res) 。然后中间件 protect 也被调用了。 然而,中间件会抛出一个错误,并且该错误由 Express 默认错误处理程序处理,然后将错误写入客户端,然后结束请求。因此,相同的请求不会进入路由处理程序,因此它也不会打印任何控制台日志。

…我收到了 500 错误….

Ans: 当错误代码超出 4xx 或 5xx 范围时,响应状态代码将被设置为 500。这是 Express 中默认的错误处理方式。

调试此案例:

请使用 Express 抛出的堆栈跟踪。这个可以做 显示在浏览器控制台中,如下所示的最小示例。

服务器.js

const express = require('express');
const app = express();

app.use(express.static('./'));

app.get('/a', async (req, res, next) => {
  next(new Error('Some error'));
});

app.listen(3000, () => console.log('L@3000'));

index.html 保存在项目文件夹中

<!DOCTYPE html>
<html>
  <head>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/axios.min.js"></script>
    Displaying stack-trace in the Browser console via axios
  </head>
  <bod> </bod>
  <script>
    axios
      .get('http://localhost:3000/a')
      .catch((error) => console.log(error.response.data));
  </script>
</html>

运行示例:

Run the server : node server.js

Run the browser : http://localhost:3000

// the browser console will show an HTML source code as below:

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="utf-8" />
        <title>Error</title>
      </head>
      <body>
        <pre>Error: Some error<br> &nbsp; &nbsp;at /Users/jf/Documents/JF/so/78714491/server.js:7:8<br> &nbsp; &nbsp;at Layer.handle [as handle_request] (/Users/jf/node_modules/express/lib/router/layer.js:95:5)<br> &nbsp; &nbsp;at next (/Users/jf/node_modules/express/lib/router/route.js:144:13)<br> &nbsp; &nbsp;at Route.dispatch (/Users/jf/node_modules/express/lib/router/route.js:114:3)<br> &nbsp; &nbsp;at Layer.handle [as handle_request] (/Users/jf/node_modules/express/lib/router/layer.js:95:5)<br> &nbsp; &nbsp;at /Users/jf/node_modules/express/lib/router/index.js:284:15<br> &nbsp; &nbsp;at Function.process_params (/Users/jf/node_modules/express/lib/router/index.js:346:12)<br> &nbsp; &nbsp;at next (/Users/jf/node_modules/express/lib/router/index.js:280:10)<br> &nbsp; &nbsp;at SendStream.error (/Users/jf/node_modules/serve-static/index.js:121:7)<br> &nbsp; &nbsp;at SendStream.emit (node:events:519:28)</pre>
      </body>
    </html>

复制并粘贴到浏览器中:

请将 HTML 源代码复制并粘贴到文件 error.html 中,然后在浏览器中查看该文件。它将显示如下。请 请注意第一行,它表示错误已从第 7 行引发。

Error: Some error
    at /Users/jf/Documents/JF/so/78714491/server.js:7:8
    at Layer.handle [as handle_request] (/Users/jf/node_modules/express/lib/router/layer.js:95:5)
    at next (/Users/jf/node_modules/express/lib/router/route.js:144:13)
    at Route.dispatch (/Users/jf/node_modules/express/lib/router/route.js:114:3)
    at Layer.handle [as handle_request] (/Users/jf/node_modules/express/lib/router/layer.js:95:5)
    at /Users/jf/node_modules/express/lib/router/index.js:284:15
    at Function.process_params (/Users/jf/node_modules/express/lib/router/index.js:346:12)
    at next (/Users/jf/node_modules/express/lib/router/index.js:280:10)
    at SendStream.error (/Users/jf/node_modules/serve-static/index.js:121:7)
    at SendStream.emit (node:events:519:28)
© www.soinside.com 2019 - 2024. All rights reserved.