Replies: 1 comment
-
It depends on what data you expect, the c.req.parseBody() is when you expect multipart/form-data (like state in the documentation). But my guess is that you are using json to send the email and password. In that case you should use c.req.json() (see documentation). Also keep in mind that c.req.json() returns a const app = new Hono().post('/login', async (c, _) => {
const { email, password } = c.req.json()
// email type: any
// password type: any
}) Hope that works, and you get it running! When you've got that working, you can manually cast the email and password to strings. However that would be bad practise as you shouldn't determine what the type is, but the code should. So write a validator so you can be sure that both are a string, for instance (also see documentation): import { Hono } from 'hono'
import z from 'zod'
import { zValidator } from '@hono/zod-validator'
const loginRouteBodySchema = z.object({
email: z.string(),
password: z.string(),
})
const app = new Hono().post('/login', zValidator('json', loginRouteBodySchema), async (c, _) => {
const { email, password } = c.req.valid('json')
// email type: string
// password type: string
})
// Also export the type of the API, so we can use that in the frontend or other client
export type AppType = typeof app Now you've valid and typesafe routes with consistent errors if parameters aren't valid. One other advantage of defined these validation schema's is that we can now infer the typings from that validation in the client. Let's say you use the browser, or another backend app, you could do the following: client.ts import { hc } from 'hono/client'
import type { AppType } from '../backend' // AppType we've exported in above snippet
export const client = hc<AppType>('http://localhost:3000') And now use Well hope that helped |
Beta Was this translation helpful? Give feedback.
-
Hello, i have a question about request body. I was use express for framework, at express i usually use
const {email, password} = req.body
for request body. For now, i want to try Hono as a framework. When i use Hono, I useconst {email, password} = c.req.parseBody()
but it always show error like thisHelp me to solve this, thank you!
Beta Was this translation helpful? Give feedback.
All reactions