I’m new to NextJS and I’m trying to figure out server action.
I have this request.
import { revalidatePath } from "next/cache";
export async function submitIPCR(prevState: any, formData: FormData) {
// @ts-ignore
try {
console.log(Object.fromEntries(formData), 'waaa', formData)
const res = await fetch("http://localhost:8000/ipcr", {
method: "POST",
headers: { "Content-Type": "application/json" },
credentials: 'same-origin',
body: formData
});
console.log(res.statusText)
if (!res.ok) throw new Error('Something wrong')
await res.json()
revalidatePath('/ipcr/new');
return { message: 'Successfully' }
} catch (error) {
console.log(error)
return { message: 'Error' }
}
}
but I always get this error when I check the network.
Error: Bad request
{"message":"Unexpected token - in JSON at position 0","error":"Bad Request","statusCode":400}
I use the fetch on form like this.
const NewIPCR = () => {
const [state, formAction] = useFormState(submitIPCR, initState);
return (
<div>
<form action={formAction}>
{redacted}
</form>
</div>
);
};
export default NewIPCR;
And the confusing part is, it’s not even hitting my server. I use https://hoppscotch.io/ and my request is fine, but when I’m on nextJS I have an error. Not sure how to fix since the response is not coming from my server.
Also when I try to format the fetch request body to.
const res = await fetch("http://localhost:8000/ipcr", {
method: "POST",
headers: { "Content-Type": "application/json" },
credentials: 'same-origin',
body: {
ratee: ''
}
});
I get an overload error:
No overload matches this call.
Overload 1 of 2, '(input: RequestInfo, init?: RequestInit | undefined): Promise<Response>', gave the following error.
Object literal may only specify known properties, and 'ratee' does not exist in type 'ReadableStream<any> | Blob | ArrayBufferView | ArrayBuffer | FormData | URLSearchParams'.
Overload 2 of 2, '(input: RequestInfo | URL, init?: RequestInit | undefined): Promise<Response>', gave the following error.
Object literal may only specify known properties, and 'ratee' does not exist in type 'ReadableStream<any> | Blob | ArrayBufferView | ArrayBuffer | FormData | URLSearchParams'.ts(2769)
I didn’t even add a type on body or fetch. not sure where is this coming from.