Reputation: 161
I can't seem to get any params from a post request using Hono and Axios.
My bun hono server is simply:
import { Hono } from 'hono';
import { cors } from 'hono/cors';
const app = new Hono();
app.use('*', cors());
app.post('/products', async (c) => {
const body = await c.req.parseBody();
const { category, search } = body;
console.log('Received parameters:');
console.log(` category: ${category}`);
console.log(` search: ${search}`);
});
export default {
port: 3000,
fetch: app.fetch,
}
the react client looks like:
const data = {
category: 'electronics',
search: 'laptops',
};
axios.post('http://localhost:3000/products', data)
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
But i get undefined in the terminal:
Started server http://localhost:3000
Received parameters:
category: undefined
search: undefined
Actually, the whole body of the request is just an empty {}
.
I have also tried using c.req.param("category")
but it didn't help either...
Thanks for any help.
Upvotes: 0
Views: 1382
Reputation: 619
req.parseBody()
is for multipart/form-data
or application/x-www-form-urlencoded
body types, which it doesn't look like the axios data is formatted as.
req.param()
is for path parameters like POST /products/:category
, which the endpoint in the example isn't set up to accept and which aren't being sent with the axios POST request.
If the endpoint is expecting to receive JSON, use req.json()
instead of req.parseBody()
. Check out https://hono.dev/api/request for available body parsing options (text, etc. also available).
Upvotes: 2