簡體   English   中英

需要幫助理解邏輯

[英]Need help understanding logic

有人可以向我解釋這條線是如何工作的: https://github.com/sveltejs/realworld/blob/master/src/routes/login/index.svelte#L13

const response = await post(身份驗證/登錄, { email, password });

post是從utils.js調用的,它是這樣的:

實用程序.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());
}

所以 function 進入這里,然后獲取提供的端點,即auth/login

這讓我很困惑,因為auth/login不是端點,它是一個導出 function 的文件,位於auth/login.js下。 auth/login.js中的第二個帖子 function 會自動調用嗎? 我也不確定這個(req, res)是從哪里傳入的,因為我們只是從上面獲取這個文件,而不是傳遞任何 arguments。

身份驗證/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));
    });
}

這是在 cookie 中設置用戶的地方,我的代碼目前沒有這樣做,並且 session 在刷新時丟失。 我試圖了解如何在 Sapper 中保持會話。

此行正在調用相對路徑: const response = await post( auth/login , { email, password });

所以 fetch 調用的 url 類似於: http://yourdomain.com/auth/login

根據文檔,當調用以 in.js 結尾的路由時,Sapper 會在該文件上查找名稱為 HTTP 請求方法的 function。 更多信息:sapper.svelte.dev/docs#Server_routes

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM