Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sveltekit Post Request how to return a Response Object with non blocking database access?

I'm trying to send a POST request to a +server.js endpoint that saves the data to the database without blocking my code from execution

/** @type {import('./$types').RequestHandler} */
export async function POST({ request }) {

    request.json()
        .then((data) => {
            console.log("data: ", data);
            getConnection()
                .then((conn) => {
                    let sql = "INSERT INTO accounts (username, password, socialMediaPlatform, accountLink) VALUES (?, ?, ?, ?)";
                    let result = conn.query(sql, [data.username, data.password, data.socialMediaPlatform, data.accountLink]);
                    conn.release();

                    return new Response(JSON.stringify(result), {
                        status: 200,
                    });
            })
            .catch((err) => {
                return new Response(JSON.stringify({error: err}), {
                    status: 400,
                });
            });
        })
        .catch((err) => {
            return new Response(JSON.stringify({error: err}), {
                status: 400,
            });
        });
}

However I'm getting this error:

Invalid response from route /api/account: handler should return a Response object

But it somehow works and writes the data to the database.

Bonusquestion: I'm also getting this errormessage from vscode when hovering over the POST function Shouldn't this be typescript specific? And shouldn't the error only come if enter image description here

like image 972
0szi Avatar asked Oct 19 '25 03:10

0szi


1 Answers

You are not actually returning anything, as all the return statements are inside functions. You have to add a return at the very start (return request.json()...) and before getConnection or use await instead of chaining (which I would recommend).

TS can check JS as well, there are the flags allowJs and checkJs.

like image 85
H.B. Avatar answered Oct 20 '25 16:10

H.B.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!