Pau*_*ano 0 javascript node.js reactjs react-redux next.js
几天前我开始学习 RTK Query,我一直喜欢它很酷的功能和简单性,所以我决定在我使用 Next.js 构建的项目中从 useContext 切换到 RTK Query 以及使用 Node.js 和 Express 的自定义服务器。在这个项目中,我制作了一个用于登录和注册的 api 路由,在提供的自定义 axios 基本查询 RTK 查询的帮助下,可以使用 RTK 查询和 Axios 来实现该路由。登录和注册 api 端点已经有一个在 cookie 存储中存储令牌的逻辑。我将 RTK 查询与 axios 一起使用来发布用户请求,以便他们可以获得 cookie 存储中的令牌存储的响应。这种将用户令牌存储在 cookie 中的逻辑与 useContext 和 axios 配合得很好。但使用 RTK 查询时逻辑并未按预期工作,结果如下:
export const fetcherApi = createApi({
reducerPath: "fetcherApi",
baseQuery: axiosBaseQuery({
baseUrl: "http://localhost:5000/",
}),
tagTypes: ["User"],
endpoints(build) {
return {
//________Authentication
registerUser: build.mutation({
query: (form) => ({
url: "register",
method: "post",
data: form,
}),
invalidatesTags: ["User"],
}),
loginUser: build.mutation({
query: (form) => ({
url: "login",
method: "post",
data: form,
}),
invalidatesTags: ["User"],
}),
getAuth: build.query({
query: () => ({ url: "auth", method: "get" }),
}),
//__________User
updateUserName: build.mutation({
query: (...rest) => ({
url: "update-user",
method: "put",
data: rest,
}),
invalidatesTags: ["User"],
}),
getUser: build.query({
query: () => ({ url: "user", method: "get" }),
providesTags: ["User"],
}),
//__________Profile
postProfile: build.mutation({
query: (form) => ({
url: "login",
method: "post",
data: form,
}),
}),
getAllProfiles: build.query({
query: () => ({ url: "all-profiles", method: "get" }),
}),
getUserProfile: build.query({
query: () => ({ url: "profile/me", method: "get" }),
}),
//___________Car
postCar: build.mutation({
query: (form) => ({
url: "new-car",
method: "post",
data: form,
}),
}),
putCar: build.mutation({
query: ({ id, ...rest }) => ({
url: `update-car/{id}`,
method: "put",
data: { rest },
}),
}),
getAllCars: build.query({
query: () => ({ url: "all-cars", method: "get" }),
}),
getCarById: build.query({
query: (id) => ({ url: `onecar/${id}`, method: "get" }),
}),
getAllUserCars: build.query({
query: () => ({ url: "my-car", method: "get" }),
}),
};
},
});
export const {
// ______Authentication______
useGetAuthQuery,
useRegisterUserMutation,
useLoginUserMutation,
//_______User_________
useUpdateUserNameMutation,
useGetUserQuery,
//_____Profile_________
useGetUserProfileQuery,
useGetAllProfilesQuery,
usePostProfileMutation,
//_____Car____________
usePostCarMutation,
usePutCarMutation,
useGetAllCarsQuery,
useGetCarByIdQuery,
useGetAllUserCarsQuery,
} = fetcherApi;
Run Code Online (Sandbox Code Playgroud)
我通过添加credentials: include作为 baseQuery 参数解决了这个问题,并在我的函数中添加了 async 和 wait
baseQuery: fetchBaseQuery({
baseUrl: "https://my-app.herokuapp.com/",
credentials: "include",
}),
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6159 次 |
| 最近记录: |