我正在 NextJS 13 中构建一个 API,该 API 使用 puppetter 从 URL 参数生成屏幕截图。
这是示例代码:
import puppeteer from 'puppeteer';
import { NextResponse } from 'next/server';
export default async function GET(req, res) {
const url = req.searchParams.url;
if (!url) {
return res.status(400).json({ error: "URL parameter is required" });
}
try {
const browser = await puppeteer.launch({
headless: "new"
});
const page = await browser.newPage();
await page.goto(url);
const screenshot = await page.screenshot({
encoding: 'base64',
});
await browser.close();
return NextResponse.json(
{ status: 200 },
{ blob: `data:image/jpeg;base64,${screenshot}` },
);
} catch (error) {
console.error(error);
return NextResponse.json(
{ error: "Something went wrong" },
{ status: 500 }
);
}
}
这将返回以下错误:
Error: Objects are not valid as a React child (found: object with keys {}). If you meant to render a collection of children, use an array instead.
在执行 console.log 时,可以看到正在创建一些数据,但我不知道如何发送文件类型的响应。
关于如何通过此 API 提供二进制文件有什么建议吗?
这个问题的答案可以在这里找到,我已经修改了他们对您特定用例中的代码的建议:
import puppeteer from 'puppeteer';
import { NextResponse } from 'next/server';
export default async function GET(req, res) {
const url = req.searchParams.url;
if (!url) {
return res.status(400).json({ error: "URL parameter is required" });
}
try {
const browser = await puppeteer.launch({
headless: "new"
});
const page = await browser.newPage();
await page.goto(url);
const screenshot = await page.screenshot({
encoding: 'base64',
});
await browser.close();
const response = new NextResponse(`data:image/jpeg;base64,${screenshot}`);
response.headers.set('content-type', 'image/png');
return response;
} catch (error) {
console.error(error);
return NextResponse.json(
{ error: "Something went wrong" },
{ status: 500 }
);
}
}