【问题标题】:Fetch API promise - JavaScript and HTML connectionFetch API promise - JavaScript 和 HTML 连接
【发布时间】:2021-09-20 00:08:30
【问题描述】:

我对 HTML 和 JavaScript 非常陌生。我为登录功能创建了一个非常简单的 HTML 页面。代码如下。

<html>
    <head>
        <body>
            <form>
                <p>Username</p>
                <input type='text' name="" placeholder="Enter Username/Email ID">
                <p> Password</p>
                <input type='password' name="" placeholder="Enter Password">
                <input type='submit' name="" value="LogIn the User">
            </form>         
        </body>
    </head>
</html>

现在我有一个具有登录功能的 RESTful API。我可以在 POSTMAN 中以 json 格式发送用于 API 测试的用户名和密码的值。

现在我的问题是如何将登录 API 的其余部分与我的 HTML 页面连接起来。如果这是一个重复的问题,那么请把我带到原来的问题。另外,如果您可以建议一些资源。我经历了很多,但找不到相关的。 谢谢。

【问题讨论】:

    标签: javascript html css api post


    【解决方案1】:

    基本步骤是

    1. 拦截表单上的提交事件
    2. 解析表单以创建您要提交的 JSON
    3. 提交json
    4. 对响应做一些事情

    document.forms[0].addEventListener('submit', function(e) { // when they submit
        e.preventDefault(); // Don't try and submit the form the traditional way
        const data = {
            username: e.target.querySelector('input[name="username"]').value,
            password: e.target.querySelector('input[name="password"]').value
        } // get the JSON we want to submit
        fetch('/auth/login', {
            method: 'post', // submit it as a post request
            body: JSON.stringify(data)
        }).then(function(response) {
            return response.json(); // parse the response as json
        }).then(function(data) {
            console.log('do something with the response');
        });
    });
    <html>
        <head>
            <body>
                <form>
                    <p>Username</p>
                    <input type='text' name="username" placeholder="Enter Username/Email ID">
                    <p> Password</p>
                    <input type='password' name="password" placeholder="Enter Password">
                    <input type='submit' value="LogIn the User">
                </form>         
            </body>
        </head>
    </html>

    【讨论】:

      猜你喜欢
      • 2017-10-22
      • 2019-07-23
      • 1970-01-01
      • 2019-12-19
      • 1970-01-01
      • 2022-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多