Next.js Discord

Discord Forum

Route request not available

Unanswered
Atlantic cod posted this in #help-forum
Open in Discord
Avatar
Atlantic codOP
//api/test/route.js
export async function POST(request) {
const res = await request.json()
const formData = await request.formData()
console.log("route post test:"+ res);
console.log("route post Request:"+ formData);
console.log("route post request:"+ JSON.stringify(request));

return Response.json({ status: 200, res});
}
//app/page.js
const response = await fetch('/api/test', {
method: 'POST',
body: {prompt},

});

All logs show empty strings. Not sure what I'm doing wrong here.

My guess is that I'm building the fetch call wrong somehow.

"next": "14.2.5"

4 Replies

Avatar
@Atlantic cod I believe you are doing client-side data fetching, right? as you are using relative api path
can you show me your page.ts?
Avatar
Atlantic codOP
yes, the page is mark with "use client".

Btw I manage to fix it but switching away
from the route.js file towards a lib/test.js

Basically:

//lib/test.js
"use server"
export async function test(prompt){}

//app/page.js
"use client"

import { useState } from 'react';
import {test} from './api/test'

export default function Home() {
const [prompt, setPrompt] = useState();
async function tester() {
try {
console.log(prompt);
const data = await test(prompt);
console.log("response:"+ JSON.stringify(data));
} catch (error) {
console.error('Error generating images:', error);
}
}

return (
<form action={tester}>...<form>)

As per page it was a simple example just to test the access to the server side functions.
Avatar
yeah, it supposed to be server action - not api route