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
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With