首页 > 解决方案 > axios.post 未从服务器返回数据:“无法解构‘(中间值)’的属性‘数据’,因为它未定义”

问题描述

我正在尝试通过 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);

标签: javascriptreactjsexpressgetaxios

解决方案


您在这里有一些额外的花括号(或缺少return,取决于您如何看待它)。当您使用带有花括号的 lambda(箭头函数)时,您必须显式返回一个值,否则它将返回 undefined。从此更改您的代码:

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

到其中之一:

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

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

任何一种格式都将返回实际的 axios 承诺,而不是默认的未定义。


推荐阅读