redux 使用createApi(nodejs)处理端点请求时发生未处理的错误

aamkag61  于 2023-08-05  发布在  其他
关注(0)|答案(2)|浏览(127)

我使用RTK Query在nodejs环境中以纯JavaScript(没有react)获取和缓存数据。enter image description here我使用的是Redux官方网站上的代码。唯一的变化是我在fetchBaseQuery中包含了fetchFn,因为node-fetch没有被检测为默认函数。当我尝试这样做时,我遇到了这个错误,它说处理端点getPokemonByName的请求时发生了未处理的错误****在未处理的错误的情况下,没有标签将被“提供”或“无效”。参考错误:标题未定义
我不知道如何将我自己的自定义函数作为fetchFn传递给fetchBaseQuery。我不确定createApi中fetchFn和queryFn的区别。如果有人能帮我
1.将creatApi与一个自定义函数一起使用,该函数接受url和选项作为输入并获取数据
1.使用选择器打印获取的数据而不使用钩子

mzsu5hc0

mzsu5hc01#

fetch API是浏览器原生的,在nodejs中不可用。你看到的错误是由于rtk-query依赖于fetch API。为了使用fetch API,您需要在项目中全局填充它,以便rtk库可以像在浏览器中一样使用它
下面可以看到一种方法

import fetch, { Headers } from 'node-fetch'

globalThis.fetch = fetch;
globalThis.Headers = Headers;

字符串

ibps3vxo

ibps3vxo2#

下面是一个如何让rtk-query在nodejs中运行的工作示例
下面列出了在nodejs中实现这一点的关键要素

  1. nodejs的polyfill window.fetch
    1.自定义设置将{ fetchFn }传递给fetchBaseQuery
    1.使用不带钩子的rtk查询意味着分散存储并向其分派rtk查询的预定义操作,例如api.endpoints.getCharacters.initiate()
    index.js
import { getCharacters } from "./store/characterService.js";
import fetch, { Headers, Request } from "node-fetch";

globalThis.fetch = fetch;
globalThis.Headers = Headers;
globalThis.Request = Request;

const init = async () => {
  const data = await getCharacters();

  console.log(data);
};

init();

字符串
store.js

import redux from "@reduxjs/toolkit";
import reduxQuery from "@reduxjs/toolkit/dist/query/index.js";
import fetch from "node-fetch";

export const api = reduxQuery.createApi({
  reducerPath: "api",
  baseQuery: reduxQuery.fetchBaseQuery({
    baseUrl: "https://rickandmortyapi.com/api",
    fetchFn: (...args) => {
      return fetch(...args);
    },
  }),
  endpoints: (builder) => ({
    getCharacters: builder.query({
      query: () => "/character",
    }),
    getCharacter: builder.query({
      query: (id) => `/character/${id}`,
    }),
  }),
});

let store = null;

const initiateStore = () => {
  store = redux.configureStore({
    reducer: {
      [api.reducerPath]: api.reducer,
    },
    middleware: (getDefaultMiddleware) =>
      getDefaultMiddleware().concat(api.middleware),
  });
};

export const getStore = () => {
  if (!store) {
    console.log(store);
    initiateStore();
  }
  return store;
};


characterService.js

import { getStore, api } from "./store.js";

export const getCharacters = async () => {
  const store = getStore();
  const { data } = await store.dispatch(api.endpoints.getCharacters.initiate());
  return data;
};

export const getCharacter = async (id) => {
  const store = getStore();
  const { data } = await store.dispatch(
    api.endpoints.getCharacter.initiate(id)
  );
  return data;
};


此外,fetchFn是用于配置BaseQuery的属性,queryFn是用于配置单个端点并覆盖该端点的BaseQuery设置的属性

相关问题