axios.post 未从服务器返回数据:"Cannot destructure property 'data' of '(intermediate value)' as it is undefined"

axios.post not returning data from server: "Cannot destructure property 'data' of '(intermediate value)' as it is undefined"

我正在尝试通过 axios.post() 从服务器获取数据。

决定使用 POST 而不是 GET,因为我想发送一个带有 ID 的数组以在数据库中查找,这可能太大而无法放入 GET 查询参数。

我设法在 POST 的正文中发送了一个带有 id 的数组。这到达了我的服务器。我可以成功地找到数据库中的项目。然后在响应中返回这些项目。数据显示在 Chrome devtools > Network(状态 200)中。使用 Postman 手动发送请求时,我也得到了正确的东西。

似乎一切正常,但响应没有到达我在 axios 函数中的数据变量。

我花了一天的时间尝试解决所有类似问题的答案。没有任何效果...

我也试过 GET 并改为在查询参数中发送 ID,这给出了同样的错误。我怀疑我对 async/await 做错了什么,因为我得到了这个“中间值”。

在此先感谢您的帮助。

客户端 axios 函数

const url = 'http://localhost:5000';

export const getStuff = Ids => {
  axios.post(
    `${url}/cart/stuff`,
    {
      Ids: Ids,
    },
    {
      headers: {
        'Content-Type': 'application/json',
      },
    }
  );
};

客户操作

import * as api from '../api';

export const getStuff = Ids => async dispatch => {
  try {

    // Ids is an array like ["5fnjknfdax", "5rknfdalfk"]

    const { data } = await api.getStuff(Ids);
    // this gives me the error in the title, data never comes through

    //dispatch(-dolater-);

  } catch (error) {
    console.log(error);
  }
};

服务器控制器

export const getStuff = async (req, res) => {
  try {
    const { Ids } = req.body;
    const stuff = await STUFF.find().where('_id').in(Ids);
    console.log('SERVER', stuff);
    // this works until here. request comes through and
    // I can successfully find the stuff I want in the database
    res.status(200).json(stuff); // this also works, response is being sent
  } catch (error) {
    res.status(404).json({ message: error });
  }
};

服务器路由

router.post('/cart/stuff', getStuff);

你这里有一些额外的大括号(或者缺少 return,这取决于你如何看待它)。当你使用带大括号的 lambda(箭头函数)时,你必须明确地 return 一个值,否则它将 return 未定义。从此更改您的代码:

export const getStuff = Ids => {
  axios.post(...);
};

其中之一:

// Option 1
export const getStuff = Ids => {
  return axios.post(...);
};

// Option 2
export const getStuff = Ids => axios.post(...);

任何一种格式都将 return 实际的 axios promise,而不是默认的 undefined。