0

As the title suggest, I get a weird error when responding with data from my server.

In homepage.js (which I want to load after loggin in) I have this request to the server to get the posts and then set the posts to the response.

useEffect(() => {
//userService.getDashboard() === Axios.get('http://localhost:3001/homepage')
    userService.getDashboard().then((response) => {
        setListOfPosts(response)
    });
}, []);

This request first goes to the homepage.js, which further sends a request to getPosts, like so:

    const headers = req.headers;
    const getPosts = Axios.get('http://localhost:3001/getPosts', {headers: headers});

    getPosts.catch((response) => {
        //NEVER GET ANY RESPONSE???
        console.log('Error in homepage.js')
        //res.send(response);
    });

    getPosts.then((response) => {
        //NEVER GET ANY RESPONSE???
        res.send(response.data);
    });

And lastly in the chain I have the getPosts router which does:

router.get('/', authenticateToken, async (req, res) => {
    await db.query('SELECT * FROM posts', 
    (err, result) => {
        if (err) {
            console.log('HELLO FROM ERROR')
            res.send({errorMessage: err});
        } else {
            console.log(result)
            res.send(result);
        }
    });
}); 

So I can confirm that after every request to homepage I get all the way to getPosts() and the database query always works fine and goes into the result where "console.log(result)" lies and I can confirm that the result is indeed all the posts. The weird stuff happens when I'm sending back the data. So from getPosts() I'm obviously doing a res.send(result) which sends the data back to homepage.js. But this is when I get the error "UnhandledPromiseRejectionWarning: Error: Request failed with status code 304"

Any idea why?

Kevin. J
  • 35
  • 8

1 Answers1

1

you should not use res.send inside the .then of axios

this code works for me

  useEffect(() => {
    getPosts.then((response) => {
      console.log("inside getPosts.then ");
      console.log(response);
    });

and this is my controller file to send request to backend:

const axios = require("axios");

export const getPosts = axios.get("http://localhost:5000/tasks/taskscheck");

getPosts.catch((response) => {
  console.log("Error in homepage.js");
});

getPosts.then((response) => {
  console.log("inside then get posts");
  console.log(response);
});

I have tasks project and I can see in the response all my tasks.

Micahel Hamami
  • 179
  • 1
  • 10
  • Thanks, this does work! However, what I wanted to do was make a request to "http://localhost:3001//homepage" that basically bundles several other requests. But you might not be able to do that? – Kevin. J Sep 17 '21 at 14:21
  • I don't think it is good practice to do 2 requests , especially if it is client requests. maybe you want to do controllers in between to make a cleaner code. – Micahel Hamami Sep 18 '21 at 17:49