evirac
evirac

Reputation: 63

Axios GET request to fetch tweets for specific user, returns 500 error, route not being reached

I'm working on a Twitter clone and encountering an issue with fetching tweets for the authenticated user. Despite having a valid token and other routes working correctly, the /tweets/user route is not being reached and I get a 500 error. No logs from the route appear in the terminal.

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 file: VITE_API_URL=http://localhost:5000

Axios Request URL in Profile.jsx:

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

I know that,

Error I'm getting:

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, …}

What could be causing the /tweets/user route to not be reached, resulting in a 500 error?

Thanks!

Upvotes: 0

Views: 90

Answers (1)

WeDoTheBest4You
WeDoTheBest4You

Reputation: 1897

/tweets/user route is not being reached…: …No logs from the route appear in the terminal….

Ans: The request finds the route - router.get('/user', protect, async (req, res) . And then the middleware protect has been invoked as well. However the middleware throws an error and this error is handled by Express default error handler, and it then writes the error to the client and then ends the request. Therefore the same request does not enter into the route handler and thus it does not print any console logs as well.

… and I get a 500 error….

Ans: When the error code is outside the 4xx or 5xx range, then the response statuscode will be set to 500. This is the default error handling way in Express.

To debug this case:

Please use the stack-trace thrown by Express. This can be made displayed in the Browser console as shown below by a minimal example.

server.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 kept in the project folder

<!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>

Running the example:

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>

Copy & Paste in Browser :

Please copy and paste the HTML source into a file error.html and view the same in Browser. It would display as below. Please note the first line, it says the error has been thrown from line 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)

Upvotes: 0

Related Questions