I made an api to get the preview of Url, but I get an error.
Unanswered
West African Crocodile posted this in #help-forum
West African CrocodileOP
I created an api to get a preview of Url.
It works fine in the development environment, but in the production environment hosted on vercel, I get a POST 405 (Method Not Allowed) error. What should I do?
It works fine in the development environment, but in the production environment hosted on vercel, I get a POST 405 (Method Not Allowed) error. What should I do?
export async function POST(request: NextRequest) {
try {
const body = await request.json();
const url = body.url;
if (!url) {
return NextResponse.json(
{
message: 'Bad request',
error: 'URL is required in the request body',
},
{
status: 400,
},
);
}
let response;
try {
response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
} catch (fetchError) {
return NextResponse.json(
{
message: 'Error in fetching URL',
},
{
status: 502, // Bad Gateway
},
);
}
const html = await response.text();
const $ = cheerio.load(html);
const title =
$('meta[property="og:title"]').attr('content') || $('title').text();
const description =
$('meta[property="og:description"]').attr('content') ||
$('meta[name="description"]').attr('content');
const image = $('meta[property="og:image"]').attr('content');
return NextResponse.json({
title,
description,
image,
} as LinkPreviewResponseEntity);
} catch (error) {
return NextResponse.json(
{
message: 'Internal Server Error',
error:
error instanceof Error ? error.message : 'An unknown error occurred',
},
{
status: 500, // Internal Server Error
},
);
}
}