I have these files in my NextJS app. Please note that I am new to NextJS 13
, and have tried searching online, tutorials to catch up with the new updates, and see if I can resolve this myself, but seems that effort is to no avail.
The endpoint that I am trying to make a request to is as follows src/app/contact-route/route.js
with this code:
export async function postHandler(req, res) {
try {
const { data } = req.body;
console.log("DATA FROM BCK", data);
res.status(200).json({ message: 'Data received successfully!' });
} catch (error) {
res.status(500).json({ error: 'failed to load data' });
}
}
export default async function handler(req, res) {
if (req.method === "POST") {
return postHandler(req, res);
} else {
res.status(405).json({ message: 'This method is not allowed' });
}
}
And my contact page src/app/contact/page.js
file has this in it:
export default function Contact() {
const [data, setData] = useState({
fullName: "",
email: "",
phone: "",
message: ""
});
const handleChange = (e) => {
e.preventDefault();
const { name, value } = e.target;
setData(prevData => ({
...prevData,
[name]: value
}));
}
const handleSubmit = async (e) => {
e.preventDefault();
try {
const baseUrl = `/app/contact-route`;
const response = await fetch(baseUrl, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ data })
});
const contactData = await response.json();
console.log(contactData);
} catch (error) {
console.log(error);
}
}
return (
<div>
<div >
<div>
<div >
<form onSubmit={handleSubmit}>
<div>
<label htmlFor="full-name">
Full name
</label>
<input
type="text"
name="full-name"
id="full-name"
onChange={handleChange}
autoComplete="name"
/>
</div>
<div>
<label htmlFor="email">
Email
</label>
<input
id="email"
name="email"
type="email"
onChange={handleChange}
autoComplete="email"
placeholder="Email"
/>
</div>
<div>
<button type="submit">
Submit
</button>
</div>
</form>
</div>
</div>
</div>
</div>
)
}
The issue I am having is that making a POST
request to the endpoint src/app/contact-route/route.js
throws a few errors:
⨯ Detected default export in '/Users/path-to-file/src/app/contact-route/route.js'. Export a named export for each HTTP method instead.
⨯ No HTTP methods exported in '/Users/path-to-file/src/app/contact-route/route.js'. Export a named export for each HTTP method.
and
POST http://localhost:3000/app/contact-route 404 (Not Found)
handleSubmit @ page.js:28
SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON
Can you help me resolve this issue. Much thanks
2
Answers
You were almost right!
In next.js 13 API functions name must be one of the http methods (GET, POST, DELETE…)
if you will check you network you will see you git 405 (method not allowed)
just change
export async function postHandler(req, res) {
to
export async function POST(req, res) {
to be clear, if you want it to be a get request the function name must be
GET(req,res)
if you want it to support multiple methods all you need to do is:
In your
route.js
rename your exported function from:to:
Also for your result you don’t need the second parameter, you can return a NextResponse like: