hono icon indicating copy to clipboard operation
hono copied to clipboard

Body is not forwarded

Open monstermichl opened this issue 6 months ago • 0 comments

What version of Hono are you using?

4.5.6

What runtime/platform is your app running on?

Bun

What steps can reproduce the bug?

I'm listening to a specific POST route and want to forward the request to another service. However, the body doesn't get forwarded. I found this issue in which forwarding should be possible using fetch. The request itself gets forwarded, but the body in the receiving handler is empty.

Forwarding

import type { Context } from 'hono';

export async function newUserHandler(context: Context) {
    return fetch('http://auth-service/users', context.req.raw);
}

Auth service handler

import type { Context } from 'hono';
import type { ErrorDto } from '../dtos/error-dto';
import { StatusCodes } from 'http-status-codes';
import type { AnyObject, InferType, Maybe, ObjectSchema, ValidationError } from 'yup';
import { createError } from '../helpers/error-helper';

export function httpHandler<T extends ObjectSchema<Maybe<AnyObject>>>(schema: T, handler: (object: InferType<T>, context: Context) => any) {
    return async (context: Context) => {
        let validatedObject: InferType<T>;
        let error: ErrorDto | undefined;

        if (!schema) {
            error = createError('No schema has been provided');
        } else if (!handler) {
            error = createError('No handler has been provided');
        } else {
            /* Make sure a valid JSON has been received. */
            try {
                const object = await context.req.json();

                try {
                    validatedObject = await schema.validate(object);
                } catch (validationError) {
                    error = {
                        messages: (validationError as ValidationError).errors,
                    } as ErrorDto;
                };
            } catch (e) {
                error = createError(e!.toString());
            }
        }
        return error ? context.json(error, StatusCodes.INTERNAL_SERVER_ERROR) : handler(validatedObject!, context);
    }
}

Output

auth-service         | ----------> 

What is the expected behavior?

Maybe I misunderstood the mentioned approach but from what I understand the whole request should be forwarded, including the body.

What do you see instead?

No response

Additional information

I also checked if the forwarding services receives the body and there I can see it.

No response

monstermichl avatar Aug 19 '24 11:08 monstermichl