Search code examples
httprequestsveltesveltekit

SvelteKIt: getting an error "Handler should return a response", though I am returning one?


I have a simple API endpoint server function that imitates an authorization POST request:

/** @type {import('./$types').RequestHandler} */

import { json, error } from '@sveltejs/kit'

export async function POST({ request }) {
    const data = await request.json()

    if (!data.username || !data.password) {
        return error(400, 'Missing username or password.')
    }

    return json({ username: data.username, id: 1 })
}

And a form that uses this function in +page.svelte:

async function login() {
        const response = await fetch('/api/auth/login', {
            method: 'POST',
            body: JSON.stringify({
                username,
                password
            })
        })
        const resJSON = await response.json()
        console.log('Form submitted', resJSON)
    }

But I'm getting an error in the terminal: Error: Invalid response from route /api/auth/login: handler should return a Response object.

Am I not returning an object in json({})?


Solution

  • The function error() does not return anything returnable. It, in fact, returns an exception that you must throw so, changing line

    return error(400, 'Missing username or password.')
    

    To this

    throw error(400, 'Missing username or password.')
    

    Will fix your problem