next.js 为什么下一个Js13JSON.parse返回字符串它会返回对象

ruarlubt  于 2023-06-05  发布在  其他
关注(0)|答案(1)|浏览(118)

谁能告诉我为什么dbJson类型返回字符串它应该返回对象

export async function POST(req: Request) {
  const data = (await req.json()) as { type: "print" | "view" | "save" };
  let db = await ReadDb();
  let dbJson = JSON.parse(db) as dbSchema;
  console.log(typeof dbJson);
  if (data.type === "print") {
    dbJson.printResume = dbJson.printResume + 1;
  } else if (data.type === "save") {
    dbJson.savePdf = dbJson.savePdf + 1;
  } else if (data.type === "view") {
    dbJson.pageView = dbJson.pageView + 1;
  }
  SaveDb(dbJson);
  return NextResponse.json({ status: "Ok" });
}
async function ReadDb() {
  const jsonDirectory = path.join(process.cwd(), "json");
  const db = await fs.readFile(process.cwd() + "/public/db.json", "utf-8");

  return db;
}
async function SaveDb(newDb: dbSchema) {
  const db = await fs.writeFile(
    process.cwd() + "/public/db.json",
    JSON.stringify(newDb)
  );
}

控制台

string
- error TypeError: Cannot create property 'printResume' on string '{"pageView":0,"printResume":0,"savePdf":0}'
    at POST (webpack-internal:///(sc_server)/./app/api/views/route.ts:26:28)
    at async eval (webpack-internal:///(sc_server)/./node_modules/next/dist/server/future/route-modules/app-route/module.js:242:37)

有谁能告诉我为什么会发生这种情况我该如何解决这个问题

f1tvaqid

f1tvaqid1#

所有的一切都是在打印日志兄弟

'{"pageView":0,"printResume":0,"savePdf":0}'

这是一个字符串:)
所有都与ReadDb()函数有关
我想你用的是sqlite,而sqlite不支持json和object

相关问题