我在后端收到此错误:
创建错误:SyntaxError:JSON 中位置 1 处减号后没有数字(第 1 行第 2 列) 在 JSON.parse() 在 parseJSONFromBytes (节点:内部/deps/undici/undici:4292:19) 在 successSteps(节点:内部/deps/undici/undici:4274:27) 在 fullReadBody (节点:内部/deps/undici/undici:2695:9) 在 process.processTicksAndRejections (节点:内部/进程/task_queues:95:5) 在异步消费主体(节点:内部/ deps/undici/undici:4283:7) 在异步 POST (webpack-internal:///(rsc)/./app/api/admin/products/route.ts:94:29)
这是我的路由器代码:
import { NextResponse } from "next/server";
import { connectMongoDB } from "@/app/lib/mongodb";
import { getServerSession } from "next-auth";
import Product from "@/app/lib/models/product";
import path from "path";
import fs from "fs";
export const dynamic = 'force-dynamic';
export const revalidate = 0;
function slugify(text: string): string {
return text
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/(^-|-$)+/g, "");
}
export async function POST(req: Request) {
try {
await connectMongoDB();
const session = await getServerSession();
if (session?.user?.email !== process.env.ADMIN_EMAIL) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
const productData = await req.json();
let bannerPath = "";
if (productData.banner) {
const matches = productData.banner.match(/^data:(.+);base64,(.+)$/);
if (matches) {
const [, mimeType, base64Data] = matches;
const fileExt = mimeType.split("/")[1];
if (!["jpeg", "jpg", "png", "webp"].includes(fileExt)) {
return NextResponse.json(
{
error:
"Invalid file format. Only JPEG, JPG, PNG, and WEBP are allowed.",
},
{ status: 400 }
);
}
const uploadDir = path.join(process.cwd(), "public", "banner");
if (!fs.existsSync(uploadDir)) {
fs.mkdirSync(uploadDir, { recursive: true });
}
const slugifiedName = slugify(productData.name || "product");
const filename = `${slugifiedName}.${fileExt}`;
const filepath = path.join(uploadDir, filename);
const buffer = Buffer.from(base64Data, "base64");
fs.writeFileSync(filepath, buffer);
bannerPath = `/banner/${filename}`;
}
}
const { ...createData } = productData;
if (bannerPath) {
createData.banner = bannerPath;
}
const newProduct = await Product.create(createData);
return NextResponse.json(newProduct);
} catch (error) {
console.error("Create error:", error.stack);
return NextResponse.json(
{ error: "Failed to create product" },
{ status: 500 }
);
}
}
这就是有效负载:
{
"name": "title",
"subtitle": "subtitle",
"status": "Active",
"description": "description",
"durations": [
{
"lemonId": "123456",
"days": "30",
"name": "Name",
"value": "USD30.00",
"buy_now_url": "URL IN HERE"
},
{
"lemonId": "654321",
"days": "7",
"name": "Name",
"value": "USD30.00",
"buy_now_url": "URL IN HERE"
}
],
"functions": [
"1231231"
],
"requirements": [
{
"text": "213241421"
}
],
"banner": "The base64 data is here (I converted the data to png and verified it and the base64 is correct)."
}
我使用这些版本:
Next.js:14.2.22
Node.js:v21.7.3
我想我知道为什么会发生这种情况。我不完全确定,但我相信这就是原因。
durations 数组似乎包含具有 days 和柠檬Id 等属性的对象。理想情况下,这些应该是数字,但如果它们没有在前端被正确解析,它们在发送之前可能最终会成为包含无效字符的字符串(例如单引号或其他非数字元素)。
另外,也可能是网络问题。即使前端发送完美的 JSON,网络故障也可能会损坏它。我知道这是因为它发生在我身上。
如果这两个都不是问题,则可能是由于前端和 API 路由之间的中间件或代理造成的。另一种可能性是前端正在发送带有非 ASCII 字符的数据。