需要帮助理解逻辑
Need help understanding logic
有人可以向我解释一下这条线是如何工作的吗:
https://github.com/sveltejs/realworld/blob/master/src/routes/login/index.svelte#L13
const response = await post(
auth/login, { email, password });
post
正在从 utils.js
调用,即:
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());
}
所以函数进入这里,然后获取提供的端点,即auth/login
。
这让我很困惑,因为auth/login
不是一个端点,它是一个导出函数的文件,在auth/login.js
下。 auth/login.js
中的第二个 post 函数会自动调用吗?我不确定这个 (req, res)
也从哪里传入,因为我们只是从上面获取这个文件而不传递任何参数。
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));
});
}
这是在 cookie 中设置用户的位置,我的代码当前没有这样做,并且会话在刷新时丢失。我想了解如何在 Sapper 中保持会话。
此行正在调用相对路径:
const response = await post(auth/login
, { email, password });
所以 fetch 调用的 url 类似于:http://yourdomain.com/auth/login
根据文档,调用以 .js 结尾的路由时,Sapper 在该文件上查找具有 HTTP 请求方法名称的函数。
更多信息:sapper.svelte.dev/docs#Server_routes
有人可以向我解释一下这条线是如何工作的吗: https://github.com/sveltejs/realworld/blob/master/src/routes/login/index.svelte#L13
const response = await post(
auth/login, { email, password });
post
正在从 utils.js
调用,即:
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());
}
所以函数进入这里,然后获取提供的端点,即auth/login
。
这让我很困惑,因为auth/login
不是一个端点,它是一个导出函数的文件,在auth/login.js
下。 auth/login.js
中的第二个 post 函数会自动调用吗?我不确定这个 (req, res)
也从哪里传入,因为我们只是从上面获取这个文件而不传递任何参数。
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));
});
}
这是在 cookie 中设置用户的位置,我的代码当前没有这样做,并且会话在刷新时丢失。我想了解如何在 Sapper 中保持会话。
此行正在调用相对路径:
const response = await post(auth/login
, { email, password });
所以 fetch 调用的 url 类似于:http://yourdomain.com/auth/login
根据文档,调用以 .js 结尾的路由时,Sapper 在该文件上查找具有 HTTP 请求方法名称的函数。 更多信息:sapper.svelte.dev/docs#Server_routes