Home > database >  Type '() => { body: string; status: number; }' is not assignable to type svelte
Type '() => { body: string; status: number; }' is not assignable to type svelte

Time:01-22

trying to make a basic api endpoint of svelte using RequestHandler from index.json.ts file

import type { RequestHandler } from '@sveltejs/kit'

export const get: RequestHandler = () => {
    return{
        body:'Hello from api.',
        status:200
    }
}

and getting errors:

Type () => { body: string; status: number; } is not assignable to type RequestHandler<Partial<Record<string, string>>, string | null>.
  Type { body: string; status: number; } is not assignable to type MaybePromise<Response>.
    Type { body: string; status: number; } is missing the following properties from type Response: headers, ok, redirected, statusText, and 9 more. ts(2322)

tried making an endpoint accessible to the project yet keep getting these errors

CodePudding user response:

In current versions of SvelteKit there are multiple issues here:

  • Custom endpoints have to be in server.ts/js files
  • The name of the handler has to be all-caps
  • The handler has to return a full Response object, as can be seen in the type error

So in a server.ts:

import type { RequestHandler } from '@sveltejs/kit';

export const GET: RequestHandler = () => {
    return new Response(
        'Hello from api.',
        { status: 200 }
    );
};
  • Related