Кажется, я не понимаю маршрутизацию [закрыто]Javascript

Форум по Javascript
Ответить
Anonymous
 Кажется, я не понимаю маршрутизацию [закрыто]

Сообщение Anonymous »

Привет, ребята, у меня проблема с маршрутом API в next js. В основном пытаюсь получить мой документ из MinIO (хранилище файлов), затем использовать langchain для преобразования в векторы, а затем передать в pineconeDB
api/create-chats/route.ts

Код: Выделить всё

import { loadMinioIntoPinecone } from "@/lib/pinecone";
import { NextRequest, NextResponse } from "next/server";

export async function POST(req: NextRequest) {
try {
// Check if the request is a form-data request
const contentType = req.headers.get("content-type");
if (!contentType || !contentType.includes("multipart/form-data")) {
return NextResponse.json(
{ error: "Invalid content type. Expected multipart/form-data." },
{ status: 400 }
);
}

// Parse request body
const formData = await req.formData();
const file = formData.get("file");
const body = await req.json();
const { file_key, file_name } = body;

// Validate required fields
if (!file || !file_key || !file_name) {
console.error("Missing required fields in the request body:", {
file,
file_key,
file_name,
});
return NextResponse.json(
{ error: "Missing required fields: file, file_key, and file_name" },
{ status: 400 }
);
}

const maxSize = 5 * 1024 * 1024; // 5MB
if (file.size > maxSize) {
return NextResponse.json(
{ error: "File size exceeds the maximum limit of 5MB." },
{ status: 400 }
);
}

// Handle file_key and file_name (e.g., store in a database, etc.)
console.log("Processing file:", { file_key, file_name });

// Load file data into Pinecone
const pages = await loadMinioIntoPinecone(file_key , file);

// Return a successful response
return NextResponse.json(
{
message: `${pages} pages processed successfully for file: ${file_name}.`,
file_key,
file_name,
},
{ status: 200 }
);
} catch (error) {
console.error("Error in POST /api/create-chats:", error);
return NextResponse.json(
{ error: "Internal server error.  Please try again later." },
{ status: 500 }
);
}
}
FileUpload.tsx

Код: Выделить всё

"use client";

import React, { useState } from "react";
import { FileUpload } from "@/components/ui/file-upload";
import { uploadToMinIO } from "@/lib/minio"; // Import the upload function
import { useMutation } from "@tanstack/react-query";
import { Loader2 } from "lucide-react";

export function FileUploadComponent() {
const [errorMessage, setErrorMessage] = useState(null); // State for error messages

const { mutate, isPending } = useMutation({
mutationFn: async ({ file_key, file_name }: { file_key: string; file_name: string }) => {
const response = new Request(`/api/create-chats`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ file_key, file_name }),
});
if (!response) {
throw new Error('Network response was not ok');
}
const responseData = await response.json();
return responseData;
},
onError: (error: Error) => {
setErrorMessage(error.message); // Set error message on mutation error
},
});

const handleFileUpload = async (uploadedFiles: File[]) => {
if (uploadedFiles.length === 0) {
console.error("No files selected.");
return;
}

try {
setErrorMessage(null); // Reset error message
const uploadPromises = uploadedFiles.map(async (file) => {
const data = await uploadToMinIO(file);
if (!data?.file_key || !data?.file_name) {
throw new Error("An error occurred during file upload.");
}
return data;
});

const uploadedFilesData = await Promise.all(uploadPromises);
uploadedFilesData.forEach((data) => {
mutate(data, {
onSuccess: (data) => {
console.log("Upload successful:", data);
},
});
});
} catch (error) {
console.error("Error uploading file to MinIO:", error);
setErrorMessage("Error uploading files. Please try again."); // Set a user-friendly error message
}
};

return (

{isPending ? (


Uploading...

) : (

{errorMessage && 
{errorMessage}
} {/* Display error message */}


)}

);
}
По правде говоря, я все еще новичок в серверной части, но я пробовал использовать различные зависимости, такие как axios, и зависимости маршрутизации по умолчанию Next, но, увы, ничего не получилось.>

Подробнее здесь: https://stackoverflow.com/questions/793 ... nd-routing
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Javascript»