问题描述
使用 Next
API 路由和 Knex
+ MysqL
,并使用 React
和 SWR
进行获取,我遇到了一个奇怪的错误。如果请求失败,我的查询开始将 ,*
附加到 select
语句,从而导致 sql 语法错误。例如,查询应使用 select *
,但结果为 select *,*
,然后是 select *,*,*
,依此类推。有没有人知道为什么会发生这种情况?
SWR 获取:
export const swrFetcher = async (...args) => {
const [url,contentType = 'application/json'] = args;
const res = await fetch(url,{
method: 'GET',headers: {
'Content-Type': contentType,},});
if (!res.ok) throw new Error(res.statusText);
const json = await res.json();
return json;
};
const { data,error } = useSWR('/api/user/me',swrFetcher,{
revalidateOnFocus: false,revalidateOnReconnect: false,revalidateOnMount: true,});
膝关节查询:
const User = knex(TABLE_NAMES.user);
export const readById = (id) => User.select('*').where({ id });
解决方法
您可能需要在函数调用中创建 knex
实例,而不是每次都重用相同的实例,就像当前发生的那样。
export const readById = (id) => {
const User = knex(TABLE_NAMES.user);
return User.select('*').where({ id });
}