0

正如标题所暗示的,当我从我的服务器响应数据时,我得到了一个奇怪的错误。

在 homepage.js(我想在登录后加载)中,我向服务器发出了这个请求以获取帖子,然后将帖子设置为响应。

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

该请求首先发送到 homepage.js,它进一步向 getPosts 发送请求,如下所示:

    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);
    });

最后在链中,我有 getPosts 路由器,它可以:

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);
        }
    });
}); 

因此,我可以确认,在每次向主页发出请求后,我都会一直到达 getPosts(),并且数据库查询始终可以正常工作并进入“console.log(result)”所在的结果,我可以确认结果确实是所有的帖子。当我发回数据时会发生奇怪的事情。所以从 getPosts() 我显然是在做一个 res.send(result) ,它将数据发送回 homepage.js。但这是当我收到错误“UnhandledPromiseRejectionWarning: E​​rror: Request failed with status code 304”的时候

知道为什么吗?

4

1 回答 1

1

你不应该在 axios 的 .then 中使用 res.send

这段代码对我有用

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

这是我向后端发送请求的控制器文件:

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);
});

我有任务项目,我可以在响应中看到我所有的任务。

于 2021-09-17T02:53:43.420 回答