How to parse req body in backend
Answered
Burmese posted this in #help-forum
BurmeseOP
I am sending form post requests to the server api. How do I extract the values? Currently I am able to get this but I am not sure how to actually get the value which is "A1A 1A1" in this case
Answered by joulev
then you still need formidable, [multer](https://www.npmjs.com/package/multer) or a similar FormData parser. read the documentation of the library you choose to see how to use it
17 Replies
BurmeseOP
@Burmese I am sending form post requests to the server api. How do I extract the values? Currently I am able to get this but I am not sure how to actually get the value which is "A1A 1A1" in this case
is this server api written in express? if so: https://www.npmjs.com/package/formidable or any FormData parser library
@joulev is this server api written in express? if so: https://www.npmjs.com/package/formidable or any FormData parser library
BurmeseOP
The api is next too, I am not using express. Shoud I figure out how to use express?
@Burmese The api is next too, I am not using express. Shoud I figure out how to use express?
no need. how do you implement your api? how did you do the above console.log?
if you use next, it is easier because it's likely you don't need a FormData parser
BurmeseOP
export default async function POST(req, res) {
console.log(req.body);
res.status('200','Property Received')
}
console.log(req.body);
res.status('200','Property Received')
}
That is all the code in my api js
@Burmese export default async function POST(req, res) {
console.log(req.body);
res.status('200','Property Received')
}
is this a route handler (route.js) or an api route (pages/api/...)?
BurmeseOP
It is an api route
This is the form submission handler
async function handleSubmit(e) {
e.preventDefault();
const form = e.target;
const formData = new FormData(form);
fetch("/api/addPropertyApi", { method: "POST", body: formData });
}
async function handleSubmit(e) {
e.preventDefault();
const form = e.target;
const formData = new FormData(form);
fetch("/api/addPropertyApi", { method: "POST", body: formData });
}
@Burmese It is an api route
then you still need formidable, [multer](https://www.npmjs.com/package/multer) or a similar FormData parser. read the documentation of the library you choose to see how to use it
Answer
BurmeseOP
Thank you so much. I wanted to ask what other way is there for handling the form submissions on backend? Is there inbuilt support in nextjs if I use route.js?
Perhaps something to do with the way I send the request?
@joulev
if you use route.js, you can simply use
await req.formData() to read the form request. but nextjs has this thing called [server actions](https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations) that can handle this for you automatically, provided you use the app routerBurmeseOP
Got it thanks a lot for your help. Can I keep this forum open to refer to it later?
sure