0
votes

Could someone please explain to me how this line works: https://github.com/sveltejs/realworld/blob/master/src/routes/login/index.svelte#L13

const response = await post(auth/login, { email, password });

post is being called from utils.js, which is this:

utils.js

export function post(endpoint, data) {
    return fetch(endpoint, {
        method: 'POST',
        credentials: 'include',
        body: JSON.stringify(data),
        headers: {
            'Content-Type': 'application/json'
        }
    }).then(r => r.json());
}

So the function enters here, and then fetches the endpoint provided, which was auth/login.

This confuses me becauseauth/login is not an endpoint, it's a file that exports a function, under auth/login.js. Does this second post function in auth/login.js get called automatically? I am unsure where this (req, res) gets passed in as well, since we are just fetching this file from above and not passing any arguments.

auth/login.js

import * as api from 'api.js';

export function post(req, res) {
    const user = req.body;

    api.post('users/login', { user }).then(response => {
        if (response.user) req.session.user = response.user;
        res.setHeader('Content-Type', 'application/json');

        res.end(JSON.stringify(response));
    });
}

This is where the user is being set in a cookie, which my code isn't currently doing, and the session is lost upon refresh. I am trying to understand how to persist sessions in Sapper.

1

1 Answers

2
votes

This line is making a call to a relative path: const response = await post(auth/login, { email, password });

So the url that fetch is calling is something like : http://yourdomain.com/auth/login

According to the docs, what happens when a route ending in .js is called is that Sapper looks for a function with the name of the HTTP request method on that file. More info here : sapper.svelte.dev/docs#Server_routes