admin管理员组

文章数量:1332383

I started learning RTK Query few days ago and I have been enjoying it cool features and simplicity, so I decided to switch from useContext to RTK Query in the project I'm building with Next.js and a custom server using Node.js and express. In this project, I made an api route for login and signup which would be hit by using RTK Query and Axios with the help of custom axios base query RTK Query provided. The login and signup api endpoints already had a logic to store token inside the cookies storage. I use RTK Query with axios to post user request so they can get a response of their token store in cookies storage. This logic of storing user token in the cookies works well with useContext and axios. But the logic didnot work as expected while using RTK Query, and these are results:

  • The token was set in the cookies storage but I get a response status of 401.
  • When user submit their credentials in the login or signup page, they are supposed to be redirected to profile page with their details being display since I made use of useQuery to fetch user profile. But the data did not display. Which means the token stored is not effective.
  • I'm unable to get the user information even though the token had been stored in the cookies.
  • Whenever I click on a link to redirect me to a particular route, useQuery didnot fetch anything and when I go back to profile, the user details will be fetched and display but when I refresh the page again, no data will be dsiplay
  • Whenever a get request was successful at the first time, I alway lose the data whenever I refresh the page.
  • All these issues only happens to routes that are protected with middleware in the backend and the middleware is to verify the token. But I have no issue with reloading a page which data that is not protected in the backend.
  • I also have a middleware in my backend for verifying and checking if token is true in the cookie to check if user is authenticated, if it is false, user should be directed to the login page in the frontend. The logic for fetching and check if data is true is inside HOC ponent which was wrapped with protected route, but whenever the data value is false, am still able to go to any route in the frontend instead of redirecting me to login page. And when I log the data to the console I recieve the correct data.
  • Removing token from cookie works successfully.
    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;

I started learning RTK Query few days ago and I have been enjoying it cool features and simplicity, so I decided to switch from useContext to RTK Query in the project I'm building with Next.js and a custom server using Node.js and express. In this project, I made an api route for login and signup which would be hit by using RTK Query and Axios with the help of custom axios base query RTK Query provided. The login and signup api endpoints already had a logic to store token inside the cookies storage. I use RTK Query with axios to post user request so they can get a response of their token store in cookies storage. This logic of storing user token in the cookies works well with useContext and axios. But the logic didnot work as expected while using RTK Query, and these are results:

  • The token was set in the cookies storage but I get a response status of 401.
  • When user submit their credentials in the login or signup page, they are supposed to be redirected to profile page with their details being display since I made use of useQuery to fetch user profile. But the data did not display. Which means the token stored is not effective.
  • I'm unable to get the user information even though the token had been stored in the cookies.
  • Whenever I click on a link to redirect me to a particular route, useQuery didnot fetch anything and when I go back to profile, the user details will be fetched and display but when I refresh the page again, no data will be dsiplay
  • Whenever a get request was successful at the first time, I alway lose the data whenever I refresh the page.
  • All these issues only happens to routes that are protected with middleware in the backend and the middleware is to verify the token. But I have no issue with reloading a page which data that is not protected in the backend.
  • I also have a middleware in my backend for verifying and checking if token is true in the cookie to check if user is authenticated, if it is false, user should be directed to the login page in the frontend. The logic for fetching and check if data is true is inside HOC ponent which was wrapped with protected route, but whenever the data value is false, am still able to go to any route in the frontend instead of redirecting me to login page. And when I log the data to the console I recieve the correct data.
  • Removing token from cookie works successfully.
    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;
Share Improve this question edited Sep 20, 2022 at 1:00 Paulliano asked Feb 25, 2022 at 13:57 PaullianoPaulliano 4441 gold badge8 silver badges16 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

I solve this issue by adding credentials: include as baseQuery parameter and I added async and await in my functions

 baseQuery: fetchBaseQuery({
    baseUrl: "https://my-app.herokuapp./",
    credentials: "include",
  }),

i had to face the error in my frontend side (using vite) i am using RTK-Query for bindings between the backend and frontend, in the backend I used node js with express.

the problem was I was storing the token in cookies in the backend side in the login controller after all validation checks like (password, email, role etc) and then I used res.cookie to store the token,

while in frontend I am using RTK- Query for fetching the data and posting data (mutation and query )

i searched lots of so-called tutorials on YouTube as well

now here is solution which never be told by anyone

in Backend app.js/ts

const corsOptions = {
origin: 'http://localhost:5173/',
methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Origin', 'X-Requested-With', 'Accept', 
'x-client-key', 'x-client-token', 'x-client-secret', 'Authorization'],
credentials: true}

app.use(cors(corsOptions))

in front end RTK-Query

  reducerPath: "userApi",
  baseQuery: fetchBaseQuery({ baseUrl: base ,credentials:"include"}),

thanks me later

本文标签: javascriptRTK Query set token inside cookies but it is not having any effectStack Overflow