Search code examples
arangodbsveltesapperpolka

Sapper & Polka Authentication


I'm trying to create a simple authentication via arangodb (arangojs) using svelte & sapper as well as polka. So I'm fairly unexperienced in the node server stuff.

In my login.svelte I'm sending a request:

const response = await fetch("/login",
{
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({username: event.target[0].value, password: event.target[1].value})
}).catch((error => console.error(error)))

This will, because of sapper call the login.ts file in the routes directory. Because I'm sending a post request it looks for a function called post:

import Database from '../server/database/index'

export async function post(req, res, next) {
    try {
        const DB = await Database.getInstance(req.body.username, req.body.password)
        await DB.createCollections()
        const sessionToken = await DB.getDatabase().login(req.body.username, req.body.password)

        if (!sessionToken) throw new Error('no session token received')

        req.session = {}
        req.session.user = true
        req.session.refresh_token = sessionToken
        res.end()
        next()

        return res
    } catch (error) {
        console.error('login.ts:post', error)
    }
}

Here I try to login into the database. On success I receive a sessionToken which, as far as I understand, I need in my frontend for "logging in".

Back in my login.svelte I receive a response. However the body is missing and I jsut don't understand why.

It might be because I forgott something in my server.ts

try {
   polka()
   .use(bodyparser.json())
   .use(
      compression({ threshold: 0 }),
      sirv('static', { dev }),
      sapper.middleware()
   )
   .listen(PORT, (err: any) => {
      if (err) console.log('error', err)
   })
} catch (error) {
   console.error('error on server API', error)
}

However I don't find much that helps me understand the issue I'm facing.

Kind regards


Solution

  • The reason why I didn't receive a response was simple. I had to add data into the res.end() function like so:

    export async function post(req, res, next) {
        try {
            const DB = await Database.getInstance(req.body.username, req.body.password)
            await DB.createCollections()
            const sessionToken = await DB.getDatabase().login(req.body.username, req.body.password)
    
            if (!sessionToken) throw new Error('no session token received')
    
            res.end(JSON.stringify(sessionToken))
            next()
    
            return res
        } catch (error) {
            console.error('login.ts:post', error)
        }
    }