He visto un tutorial para saber cómo funciona el kit de herramientas de redux después de ver que usa algún servicio de suministro de API en línea ahora que lo estoy usando, necesito personalizarlo para mi uso, así que cambié el nombre y las URL.
aquí está mi tienda.js
import {configureStore} from '@reduxjs/toolkit' import {setupListeners} from '@reduxjs/toolkit/query' import { postApi } from './actions/productAction' export const store = configureStore({ reducer:{ [postApi.reducerPath]:postApi.reducer }, // middleware:(getDefaultMiddleware)=>getDefaultMiddleware().concat(postApi.middleware), // middleware is also created for us, which will allow us to take advantage of caching, invalidation, polling, and the other features of RTK Query. middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(postApi.middleware), }) setupListeners(store.dispatch)Aquí tengo el archivo de acción que en realidad está tomando el estado de actualización de la acción
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react' export const postApi = createApi({ reducerPath:'postApi',//this is unique path which will tell the broweser where it need to store the cookie data baseQuery: fetchBaseQuery({ baseUrl:'', }), endpoints:(builder)=>({ getAllPost: builder.query({ query:()=>({ url:'http://localhost:5000/api/v1/products', method:'GET' }) }), getPostById: builder.query({ query: (id) =>({ url:`posts/${id}`, method:'GET' }) }) }) }) export const {useGetAllPostQuery,useGetPostByIdQuery} = postApiEl lugar donde estoy llamando a esta función es
import React from 'react' import {useGetAllPostQuery} from '../../actions/productAction' // import Card from '../../components/Card'; const HomePage = () => { console.log(useGetAllPostQuery()) const responseInfo = useGetAllPostQuery() console.log("the response i am getting is",responseInfo) return ( <> <h1>Hello worls</h1> </> ) } export default HomePage mi consola donde estoy recibiendo no sé por qué aparece este error, la solicitud se rechaza al mismo tiempo que mi hombre de correos trabaja en eso 
El error imagen ampliada
El problema real es
parece que no está obteniendo la URL Intente agregar su URL base de esta manera
export const postApi = createApi({ reducerPath:'postApi', baseQuery: fetchBaseQuery({ baseUrl:'http://localhost:5000/', //added your base url }), endpoints:(builder)=>({ getAllPost: builder.query({ query:()=>({ url:'api/v1/products' // this should take only one argument }) }), getPostById: builder.query({ query: (id) =>({ url:`posts/${id}` // this should take only one argument }) }) }) })Para obtener más detalles, puede consultar aquí consulta rtk
Hermano, yo también veo ese tutorial, es antiguo. Esta es la forma correcta de buscar. Por favor, hágamelo saber si esta respuesta le ayuda. Y también se completa automáticamente para importar. No está importando desde el lugar correcto si sigue ese tutorial.
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> import React from 'react' import {useGetAllPostQuery} from '../../actions/productAction' // import Card from '../../components/Card'; const HomePage = () => { console.log(useGetAllPostQuery()) //You can also desctructure it like this {data:responseInfo}, you must not directly change the value. const {data} = useGetAllPostQuery() return ( <> //Then you check if data exist first because the initial value is empty. you can also check like this <div>{data?.map((my data)=> <>...</>))}</div> <div>{data && data.map((mydata, i)=> ( //You can tag on what you want to display. if you want to display names, then you can say madata.name <p key={i}>{mydata}</p> ))}</div> </> ) } export default HomePagePara resolver errores cors, intente esto:
Cree vercel.json en la carpeta raíz.
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> { "headers": [ { "source": "/api/(.*)", "headers": [ { "key": "Access-Control-Allow-Credentials", "value": "true" }, { "key": "Access-Control-Allow-Origin", "value": "*" }, // Change this to specific domain for better security { "key": "Access-Control-Allow-Methods", "value": "GET,OPTIONS,PATCH,DELETE,POST,PUT" }, { "key": "Access-Control-Allow-Headers", "value": "X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version" } ] } ] }Vaya al archivo /api/index.js.
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> export default async (req, res) => { const { method } = req; // This will allow OPTIONS request if (method === "OPTIONS") { return res.status(200).send("ok"); } };No estaba mirando la consola correctamente, el problema principal era que el backend no me permitía consultar la API, lo cual es un poco extraño. No encontré esto usando axios, lo que significa que no necesito usar cors para acceder a la API usando axios, pero si lo estás haciendo. usando el kit de herramientas redux, entonces necesitas usar cors
npm install corsluego agregue estas líneas en su archivo backend principal
const cors = require('cors'); const express = require('express'); const app = express(); app.use(cors());