【发布时间】:2021-05-19 08:20:23
【问题描述】:
大家好,我有两个快速申请, 一个是后端,我为数据库的所有 crud 操作提供了一个 rest api。
如果我只做 GET 请求,客户端也是在一个单独的快速应用程序中构建的,我在那里使用模板来使用来自其余 api 的数据。
登录方式是在 html 模板文件中的获取请求,包含在该文件下方的脚本标记中,因为我必须为登录提交按钮设置一个 EventListener 并且必须提取用户名和密码,如果登录成功,我将令牌存储到本地存储中,并将刷新令牌存储到 cookie 中。
问题是现在我还需要 nodejs/express 端的令牌来调用 api 并将其他一些数据呈现到视图中,但是从 nodejs/express 我无法访问浏览器的本地存储。
我能在这里做什么,处理这种情况的正确方法是什么? 感谢您的帮助!
示例: 访问令牌模板中的 API 调用,位于 views 文件夹中
<body>
<div class="login-dark">
<form method="post" action="http://localhost:3007/auth/">
<h2 class="sr-only">Login Form</h2>
<div class="illustration"><i class="icon ion-ios-locked-outline" style="color: var(--success);"></i></div>
<div class="form-group"><input class="form-control" type="email" id="email" name="email" placeholder="Email">
</div>
<div class="form-group"><input class="form-control" type="password" id="password" name="password"
placeholder="Password"></div>
<div class="form-group">
<button class="btn btn-primary btn-block" id="submit" type="submit" style="background: var(--green);">Log
In
</button>
</div>
<a id="forgotPassword" class="forgot" href="#">Forgot your email or password?</a>
</form>
<img class="img-fluid" src="assetsLogin/img/thunderstorm-3430471_1920.jpg">
</div>
<script src="assetsLogin/js/jquery.min.js"></script>
<script src="assetsLogin/bootstrap/js/bootstrap.min.js"></script>
<script>
submit.addEventListener("click", async (event) => {
event.preventDefault()
let data = {
email: email.value,
password: password.value
}
await fetch('http://localhost:3007/auth', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
}).then(response => response.json())
.then(data => {
console.log(data)
if (data.token) {
document.cookie = "refreshToken=" + data.refreshtoken + "; expires=Thu, 11 Dec 2021 12:00:00 UTC";
localStorage.setItem("token", data.token)
window.location.href = 'http://localhost:3010/create';
}
else {
window.reload()
}
}
);
});
</script>
</body>
在特快路线中,我会这样做:
const express = require('express');
const router = express.Router();
router.get('/', (req, res) =>{
// here i want to fetch first the data from api
// but i need here the access token that is stored on browsers localstorage
// then i want to populate this data into the view below
res.render('view', {data from fetch});
});
【问题讨论】:
标签: javascript node.js express jwt refresh-token