我正在制作一个纯香草 JS 和 HTML SPA,您可以在其中登录,针对 API 进行身份验证,一旦您通过身份验证,您就可以访问一个服务,您可以在其中上传要更正的 CSV 文件。
我的问题是,每次用户登录时如何存储随机生成的 API 密钥?需要存储 API 密钥,以便他们可以访问同样依赖 API 调用的服务。
编辑:这是代码。
<form class="form" id="myForm">
<label for="username">Username</label>
<input type="text" name="username" id="username">
<label for="password">Password</label>
<input type="password" name="password" id="password">
<button type="submit>">LogIn</button>
</form>
<script>
// Authentication.
const myForm = document.getElementById('myForm');
myForm.addEventListener('submit', function (e) {
e.preventDefault();
const formData = new FormData(this);
const searchParams = new URLSearchParams();
for (const pair of formData) {
searchParams.append(pair[0], pair[1]);
}
fetch('https://placeholder.com/api/Authentication/Authenticate', {
method: 'POST',
mode: 'cors',
hostname: 'placeholder.com',
port: null,
path: `/api/Authentication/Authenticate?username=${username}&password=${password}`,
headers: {
"accept":"application/json"
// "apiKey": ""
},
body: searchParams,
json: true
}).then(function (response) {
return response.text();
}).then(function (text) {
console.log(text);
}).catch(function (error) {
console.error(error);
})
});
</script>