When attempting to utilize API routes in Next.js to make a POST method call to an API from the server side, I'm encountering a "Method not allowed" error.
In my page.tsx file, there is a form; upon submitting the form, it should trigger the handleSubmit
function, which in turn should invoke a function in app/api/pinToIPFS/route.js that will execute a POST method on the API. The goal is to have the API called from the server side.
"use client";
import { useState } from "react";
import "../../globals.css";
import Link from "next/link";
function CreatePage() {
const [form, setForm] = useState({ address: "", title: "", proposal: "" });
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
const formData = new FormData();
formData.append(
"file",
new Blob([JSON.stringify(form)], { type: "application/json" })
);
try {
const res = await fetch("/api/pinToIPFS", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: formData,
});
const resData = await res.json();
console.log("resData:", resData);
} catch (error) {
console.error("Error uploading file:", error);
alert("Trouble uploading file");
}
};
return (
<form
onSubmit={handleSubmit}
></form>
And here is the route.js file within api/pinToIPFS/:
export default async function handler(req, res) {
if (req.method === "POST") {
try {
const formData = req.body;
const JWT = process.env.PINATA_JWT;
const response = await fetch(
"https://api.pinata.cloud/pinning/pinFileToIPFS",
{
method: "POST",
headers: {
Authorization: `Bearer ${JWT}`,
"Content-Type": "application/json",
},
body: formData,
}
);
const data = await response.json();
res.status(200).json(data);
} catch (error) {
console.error("Error pinning file to IPFS:", error);
res.status(500).json({ error: "Error pinning file to IPFS" });
}
} else {
res.status(405).json({ error: "Method not allowed" });
}
}
An error message is displayed in the console:
page.tsx:81
POST http://localhost:3000/api/pinToIPFS 405 (Method Not Allowed)
page.tsx:94
Error uploading file: SyntaxError: Unexpected end of JSON input
at handleSubmit (page.tsx:89:33)
The code snippet from line 80-97 in page.tsx is as follows:
try {
const res = await fetch("/api/pinToIPFS", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: formData,
});
const resData = await res.json();
console.log("done!");
console.log("resData:", resData);
} catch (error) {
console.log("Error uploading file:", error);
alert("Trouble uploading file");
setUploading(false);
}
How can this issue be resolved?