node.js - 如何用 fetch api 正确替换 axios api 并映射到 nodeJS 中接收到的数据?

标签 node.js reactjs redux fetch-api node-fetch

这是整个文件的链接 - asyncActions.js

axios api部分-

const fetchUsers = () => {
  return function (dispatch) {
    dispatch(fetchUsersRrequest());
    axios
      .get("https://jsonplaceholder.typicode.com/users")
      .then((res) => {
        // res.data is the array of users
        const users = res.data.map((user) => user.id);
        dispatch(fetchUsersSuccess(users));
      })
      .catch((error) => {
        // error.message gives the description of message
        dispatch(fetchUsersFaliure(error.message));
      });
  };
};

函数输出-

{ loading: true, users: [], error: '' }
{
  loading: false,
  users: [
    1, 2, 3, 4,  5,
    6, 7, 8, 9, 10
  ],
  error: ''
}

用fetch api替换部分-

    const fetchUsers = () => {
  return function (dispatch) {
    dispatch(fetchUsersRrequest());
    fetch("https://jsonplaceholder.typicode.com/users")
      .then((res) => {
        const users = res.json().map((user) => user.id);
        console.log(users);
        dispatch(fetchUsersSuccess(users));
      })
      .catch((error) => {
        dispatch(fetchUsersFaliure(error.message));
      });
  };
};

输出-

{ loading: true, users: [], error: '' }
{
  loading: false,
  users: [],
  error: 'res.json(...).map is not a function'
}

我做错了什么?为什么我不能映射数据?

最佳答案

调用 res.json() 将返回一个 Promise。您需要添加第二个 then block :

fetch("https://jsonplaceholder.typicode.com/users")
.then((res) => res.json())
.then((res) => {
   const users = res.map((user) => user.id);
   console.log(users);
   dispatch(fetchUsersSuccess(users));
 })
.catch((error) => {
   dispatch(fetchUsersFaliure(error.message));
});

关于node.js - 如何用 fetch api 正确替换 axios api 并映射到 nodeJS 中接收到的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67163653/

相关文章:

node.js - 如何使 "npm run start"退出并显示代码 0?

javascript - 警告 : Assign object to a variable before exporting as module default

node.js - 如何使用 fetch API 解析 json 响应

node.js - 将请求从静态包代理到 Express 后端时,NginX 无法传递 POST 请求正文

javascript - 如何向 Node js中的所有连接的客户端发送广播

javascript - 为什么找不到带有 '$all' 修饰符的文档?

javascript - 尝试使用 React State 模拟 Bootstrap 导航栏折叠/展开

javascript - React useEffect 不会在路由更改时触发

javascript - React + Redux,render() 没有返回任何内容

javascript - 我需要在浏览器中显示每个水果 a 和 b