Redux 工具包突变过去 post 主体作为字符串而不是 JSON 使用 TS
Redux toolkit mutation past post body as string and not JSON using TS
堆栈:
- NextJS
- TypeScript
- Redux 工具包
- 为了
以下是使用 JS 的代码部分:
页数:
const onSubmit = async (values: UserPayload) => {
let newValues = {
...values,
birthDate: birthDate.toISOString()
}
if (user && user.id) {
newValues.id = user.id;
} else {
console.log("saving user", newValues);
try {
await createUser(newValues).unwrap();
console.log('fulfilled', newValues)
} catch (error) {
console.error('rejected', error);
}
}
}
// Redux 变异
createUser: build.mutation<UserPayload, UserPayload>({
query: (body: UserPayload) => ({
url: `/users`,
method: 'POST',
body: {...body}
}),
invalidatesTags: [{type: "User", id: "LIST"}]
}),
// NextJS API
export default async function handler(
req: NextApiRequest,
res: NextApiResponse<Partial<UserPayload> | UserPayload[]>
) {
console.log('req params', req.query);
console.log('req body', req.body);
// console.log
的输出
req params {}
req body [object Object]
saving [object Object]
同样的代码适用于 JS。请注意,当我们在突变代码中打印用户对象时,它会正确地将对象打印为 JSON。为什么它在 post 请求的主体内转换为字符串?
我发现了问题。我把content-type设为application/hal+json,应该是application/json。这是基本查询:
fetchBaseQuery({
baseUrl: `http://localhost:3000/api/`,
prepareHeaders: (headers) => {
headers.set('Authorization', `Bearer ${token}`);
headers.set('Content-Type', 'application/json');
return headers;
}
});
堆栈:
- NextJS
- TypeScript
- Redux 工具包
- 为了
以下是使用 JS 的代码部分:
页数:
const onSubmit = async (values: UserPayload) => {
let newValues = {
...values,
birthDate: birthDate.toISOString()
}
if (user && user.id) {
newValues.id = user.id;
} else {
console.log("saving user", newValues);
try {
await createUser(newValues).unwrap();
console.log('fulfilled', newValues)
} catch (error) {
console.error('rejected', error);
}
}
}
// Redux 变异
createUser: build.mutation<UserPayload, UserPayload>({
query: (body: UserPayload) => ({
url: `/users`,
method: 'POST',
body: {...body}
}),
invalidatesTags: [{type: "User", id: "LIST"}]
}),
// NextJS API
export default async function handler(
req: NextApiRequest,
res: NextApiResponse<Partial<UserPayload> | UserPayload[]>
) {
console.log('req params', req.query);
console.log('req body', req.body);
// console.log
的输出req params {}
req body [object Object]
saving [object Object]
同样的代码适用于 JS。请注意,当我们在突变代码中打印用户对象时,它会正确地将对象打印为 JSON。为什么它在 post 请求的主体内转换为字符串?
我发现了问题。我把content-type设为application/hal+json,应该是application/json。这是基本查询:
fetchBaseQuery({
baseUrl: `http://localhost:3000/api/`,
prepareHeaders: (headers) => {
headers.set('Authorization', `Bearer ${token}`);
headers.set('Content-Type', 'application/json');
return headers;
}
});