首页 > 解决方案 > 如何在 SPA 上使用随机生成的 API 密钥?

问题描述

我正在制作一个纯香草 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>

标签: javascripthtmlapisingle-page-application

解决方案


有不同的方法可以实现这一目标。

如果您希望您的 API 密钥可以在不同的会话中访问(例如,如果用户离开 SPA 并在一段时间后返回),您可以使用浏览器的本地存储

否则,您可以在 JS 的根目录中设置一个变量,并为其分配您登录后获得的 API 密钥。这样,您的变量将可以在您的 JS 中的任何地方访问,因为它的上下文是全局上下文或您的 JS .

21 年 4 月 9 日下午 2:37 编辑:

这可能是一种方法:

// Authentication.
    const myForm = document.getElementById('myForm');
    let apiKey;

    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) {
            apiKey = response.data.key; // Use the appropriate response property here.

            // You can call any function using apiKey from here.
            nextAction();
            
            return response.text();
        }).then(function (text) {
            console.log(text);
        }).catch(function (error) {
            console.error(error);
        })
    });
    
    const nextAction = () => {
      console.log(apiKey); // apiKey should be set here.
      return;
    }
<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>


推荐阅读