如何在Next 13中使用应用程序目录和RTK查询进行post请求



我如何从新的api文件夹中使用NextJS 13中的RTK查询向我的后端发出POST请求?

触发请求的正确方法是什么?我尝试了以下两种方式来调度,但都不起作用:

//first try
const dispatch = useDispatch<AppDispatch>();
dispatch(addMemoria.initiate({firstName, lastName, birthDate: selectedBirthDate, deathDate: selectedDeathDate}));
//second try
addMemoria.initiate({firstName, lastName, birthDate: selectedBirthDate, deathDate: selectedDeathDate});

预期的结果是POST请求成功并且在数据库中有一个新的memory Entry

我得到的错误:

hydration-error-info.js?32aa:27 An unhandled error occurred processing a request for the endpoint "addMemoria".
In the case of an unhandled error, no tags will be "provided" or "invalidated". Error: Invariant: Method expects to have requestAsyncStorage, none available
at headers (webpack-internal:///(:3000/e-memoria/app-client)/./node_modules/next/dist/client/components/headers.js:17:15)
at getServerSession (webpack-internal:///(:3000/e-memoria/app-client)/./node_modules/next-auth/next/index.js:94:35)
at prepareHeaders (webpack-internal:///(:3000/e-memoria/app-client)/./src/store/strapiApi.ts:23:90)
at eval (webpack-internal:///(:3000/e-memoria/app-client)/./node_modules/@reduxjs/toolkit/dist/query/rtk-query.esm.js:239:42)
at step (webpack-internal:///(:3000/e-memoria/app-client)/./node_modules/@reduxjs/toolkit/dist/query/rtk-query.esm.js:44:23)
at Object.eval [as next] (webpack-internal:///(:3000/e-memoria/app-client)/./node_modules/@reduxjs/toolkit/dist/query/rtk-query.esm.js:25:53)

下面的post请求使用我的http客户端是有效的:

POST http://localhost:1337/api/memorias
Content-Type: application/json
authorization: Bearer ****************************
{
"data": {
"firstName": "FirstNAmeTest",
"lastName": "LAstNameTest",
"birthDate": "2021-09-01",
"deathDate": "2021-09-02"
}
}

RTK store配置:

export const store = configureStore({
reducer: {
strapiApi: strapiApi.reducer,
},
middleware(getDefaultMiddleware) {
return getDefaultMiddleware().concat(strapiApi.middleware);
},
});
export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;

我的Api端点(授权的GET请求有效):

const baseQuery = fetchBaseQuery({
baseUrl: process.env.STRAPI_API_URL + '/api/', //"http://localhost:3000/api/",
prepareHeaders: async (headers, { getState }) => {
const session : any = await getServerSession(authOptions);
// If we have a token set in state, let's assume that we should be passing it.
if (session) {
headers.set('authorization', `Bearer ${session?.jwt}`)
}
headers.set('cache', 'no-store');
headers.set('Cache-control', 'no-store, max-age=0');
return headers
},
})
export const strapiApi = createApi({
reducerPath: "strapiApi",
baseQuery: baseQuery,
tagTypes: ["Memoria", "bla"],
endpoints: (builder) => ({
getAllMemorias: builder.query<{ results: Array<{ name: string }> }, void>({
query: () => `memorias`,
providesTags: ['bla'],
}),
addMemoria: builder.mutation<Memoria, Partial<Memoria>>({
query: (body: Partial<Memoria>) => ({
url: `memorias`,
method: 'POST',
body: createStrapiPOSTBody(body),
}),
invalidatesTags: [{ type: 'Memoria', id: 'LIST' }],
}),
});
export const { getAllMemorias, addMemoria } = strapiApi.endpoints;

据我所知,你只能在React Server Components中调用getServerSession。您无法访问在服务器上呈现的客户端组件中的标头。好像你现在正在从客户端组件调用它。

一般来说,您也不应该为Next SSR中的Redux存储使用export const之类的东西,因为该存储将由多个用户共享。《旅。但是,关于如何做到这一切,还没有一个好的故事——它仍然是非常实验性的。