suss
New Coder
Hi, I hope someone can help, but this question may only make sense to those familiar with Nextjs on Vercel host.
Ive posted this in the Node forum as Nextjs runs on top of Node so it was closest category
I'm not a React expert, and have really struggled to get much running in Nextjs, even though Vercel does all the hosting so I dont need to install the frameworks.
Ive started with the simplest stack example, just index html file and a function in the pages/api directory where 'backend' api code is supposed to go.
The public/index.html and pages/api/myapi.js shown below. It doesn't work. Is there anything obvious error?
And pages/api/myapi.js
Ive posted this in the Node forum as Nextjs runs on top of Node so it was closest category
I'm not a React expert, and have really struggled to get much running in Nextjs, even though Vercel does all the hosting so I dont need to install the frameworks.
Ive started with the simplest stack example, just index html file and a function in the pages/api directory where 'backend' api code is supposed to go.
The public/index.html and pages/api/myapi.js shown below. It doesn't work. Is there anything obvious error?
JavaScript:
<!DOCTYPE html>
<html>
<body>
<script>
function myPost(){
var postData = async () => {
const data = {title: "one",post: "two"};
const resp = await fetch("../pages/api/myapi.js", {
method: "POST",
body: JSON.stringify(data),
});
return resp.json();
}
myPost();
postData().then((d) => { alert(d.message) });
</script>
</body>
</html>
And pages/api/myapi.js
JavaScript:
export default function handler(req, res) {
const requestMethod = req.method;
const body = JSON.parse(req.body);
switch (requestMethod) {
case 'POST':
res.status(200).json({ message: `You submitted the following data: ${body}` })
// handle other HTTP methods
default:
res.status(200).json({ message: 'Welcome to myAPI!'})
}
}
Last edited: