admin管理员组

文章数量:1128326

I built this Next.js app that requires video conversion. Tried FFmpeg to no avail and decided to set up with Handbrake instead. This required that I utilize an API for running handbrake to convert any uploaded videos.

The API lands just fine, but I keep getting an error that the request type is invalid or (405). I have tried a few different ways of doing this and even adjusted my code according to the most recent documentation for Next.js. For some reason the POST request isn't being recognized, which is most likely because I have made some errors within my API.

import Handbrake from 'handbrake-js';
import formidable from 'formidable';
import fs from 'fs';
import { NextResponse } from 'next/server';

// Function to convert video
const convertVideo = (inputPath, outputPath) => {
  return new Promise((resolve, reject) => {
    Handbrake.spawn({ input: inputPath, output: outputPath, preset: 'Web' })
      .on('error', (err) => reject(err))
      .on('end', () => resolve(outputPath));
  });
};

// POST method to handle video conversion
export async function POST(request) {
  try {
    const form = new formidable.IncomingForm();
    form.uploadDir = './uploads';
    form.keepExtensions = true;

    return new Promise((resolve, reject) => {
      form.parse(request, async (err, fields, files) => {
        if (err) {
          resolve(NextResponse.json({ error: 'Error parsing file' }, { status: 500 }));
          return;
        }

        const inputPath = files.file.path;
        const outputPath = `${form.uploadDir}/${files.file.name}.webm`;

        try {
          await convertVideo(inputPath, outputPath);
          resolve(NextResponse.json({ success: true, outputPath }, { status: 200 }));
        } catch (error) {
          resolve(NextResponse.json({ error: 'Error converting video' }, { status: 500 }));
        } finally {
          fs.unlink(inputPath, (err) => {
            if (err) console.error('Error removing input file:', err);
          });
        }
      });
    });
  } catch (error) {
    return NextResponse.json({ error: `Unexpected error: ${error.message}` }, { status: 500 });
  }
}

本文标签: reactjsNextjs Video Conversion API Issue with HandbrakeStack Overflow