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

标签 javascript reactjs express get axios

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

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

我成功地在 POST 正文中发送了一个带有 id 的数组。这到达了我的服务器。我可以成功地找到数据库中的项目。然后,这些项目将在响应中返回。数据显示在 Chrome 开发者工具 > 网络(状态 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);
  }
};

服务器 Controller

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

最佳答案

这里有一些额外的大括号(或者缺少返回,具体取决于您如何看待它)。当您使用带有大括号的 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 Promise,而不是默认的未定义。

关于javascript - axios.post 未从服务器返回数据 : "Cannot destructure property ' data' of '(intermediate value)' as it is undefined",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65695158/

相关文章:

JavaScript 无法在 FF 或 IE 中运行

javascript - 电子邮件验证和号码长度不起作用

javascript - React.js 'this' 的组件上下文

java - jsp 表单和带有 Angular.js 验证的 servlet

javascript - 检测原始数据的变化

javascript - react : dynamic rendering of a component based on state

javascript - 即使延迟了(5秒)后,函数内部的React状态也不会改变

css - 使用express和node js添加css

javascript - 为什么 Formidable `form.parse` 回调没有在 Express 中运行?

javascript - 如何获取将数据(.emit())发送到nodejs服务器的用户的详细信息?