Making a register page with MongoDB but it keeps saying my inputs are null. This is my first time doing backend stuff with Sveltekit and I'm a bit lost. I modified this tutorial -https://stackoverflow.com/questions/69066169/how-to-implement-cookie-authentication-sveltekit-mongodb - and fixed the breaking changes but am still left with this null problem. I've also tried using e.target.value instead of bind but same thing. I'm pretty sure this problem is from register.svelte, not register.js or sitedb.js. If anyone has done anything similar please let me know, your help is appreciated. Code below:
//register.svelte
<script lang="ts">
import { createEventDispatcher } from 'svelte';
// register function
// Dispatcher for future usage in /index.svelte
const dispatch = createEventDispatcher();
// Variables bound to respective inputs via bind:value
let email;
let password;
let error;
const register = async () => {
// Reset error from previous failed attempts
error = undefined;
try {
// POST method to src/routes/auth/register.js endpoint
const res = await fetch('/auth/register', {
method: 'POST',
body: JSON.stringify({
email,
password
}),
headers: {
'Content-Type': 'application/json'
}
});
if (res.ok) {
dispatch('success');
} else {
error = 'An error occured';
}
} catch (err) {
console.log(err);
error = 'An error occured';
}
};
</script>
<input type="email" name="email" bind:value={email}>
<input type="password" name="password" bind:value={password}>
{#if error}
<p>{error}</p>
{/if}
<button on:click={register}>Register</button>
//register.js
// import stringHash from 'string-hash';
import * as cookie from 'cookie';
import { v4 as uuidv4 } from 'uuid';
import { connectToDatabase } from '$lib/sitedb';
export const post = async ({ request }) => {
// Connecting to DB
// All database code can only run inside async functions as it uses await
const body = await request.body;
const dbConnection = await connectToDatabase();
const db = dbConnection.db;
console.log(body.email);
// Is there a user with such an email?
const user = await db.collection('testUsers').findOne({ email: body.email });
// If there is, either send status 409 Conflict and inform the user that their email is already taken
// or send status 202 or 204 and tell them to double-check on their credentials and try again - it is considered more secure
if (user) {
return {
status: 409,
body: {
message: 'User with that email already exists'
}
};
}
// Add user to DB
// All database code can only run inside async functions as it uses await
await db.collection('testUsers').insertOne({
email: body.email,
password: body.password
});
// Add cookie with user's email to DB
// All database code can only run inside async functions as it uses await
const cookieId = uuidv4();
await db.collection('cookies').insertOne({
cookieId,
email: body.email
});
// Set cookie
// If you want cookies to be passed alongside user when they redirect to another website using a link, change sameSite to 'lax'
// If you don't want cookies to be valid everywhere in your app, modify the path property accordingly
const headers = {
'Set-Cookie': cookie.serialize('session_id', cookieId, {
httpOnly: true,
maxAge: 60 * 60 * 24 * 7,
sameSite: 'strict',
path: '/'
})
};
return {
status: 200,
headers,
body: {
message: 'Success'
}
};
};
CodePudding user response:
This is off:
const body = await request.body;
You need
const body = await request.json();
(I recommend using TypeScript, it would yell at you because request.body
has type ReadableStream<Uint8Array>
, which definitely has no email
property. Though, the JSON would still need to be typed manually.)