在登录应用中遍历JSON对象时遇到问题。

huangapple go评论56阅读模式
英文:

Having issues iterating through JSON object in login application

问题

I'm trying to login in with credentials that a user inputs and match them towards the API-response so I get logged in.

基本上,我正在使用API为JavaScript构建一个简单的登录应用程序。我从API获得了一个200 ok的响应,并在响应中获取了所有的帖子,我正在尝试将用户输入与其中一个帖子匹配以进行登录。我是否必须遍历每一个帖子?直观地感觉这对性能不利。那么,我应该如何继续以使代码以最佳方式运行?下面是我的JavaScript代码和HTML代码。

async function login() {
    const username = document.getElementById("username").value;
    const password = document.getElementById("password").value;
    const users = 'http://webbred2.utb.hb.se/~fewe/api/api.php?data=students';

    try {
        const response = await fetch(users, {
            method: "POST",
            body: JSON.stringify({ 
                username: username, 
                password: password 
            })
        });

        const data = await response.json();

        // Loop through the data to find a match with the user input
        let authenticated = false;  
        for(let user of users){
            if (user.username === username && user.password === password){
                authenticated = true;
                window.location.href = "quiz.html"; 
            }
            else {
                // login failed
                document.getElementById("message").innerHTML = "Incorrect username or password";
            }
        }
    } catch (error) {
        console.error(error);
        document.getElementById("message").innerHTML = "An error occurred";
    }
}

HTML代码

<!DOCTYPE html>
<html lang="sv" dir="ltr">
<head>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta charset="utf-8">
  <link rel="stylesheet" href="style.css">
  <title>Login Kursöversikt</title>
  <script src="index.js"></script>
</head>
<body>
  <div class="login">
    <h1>Logga in här för kursöversikt!</h1>
    <label for="username">Username:</label>
    <input type="text" id="username" name="username"><br><br>
    <label for="password">Password:</label>
    <input type="password" id="password" name="password"><br><br>
    <input type="button" value="Login" onclick="login()">
  </div>
  <p id="message"></p>
</body>
</html>

希望这可以帮助你。如果你有任何进一步的问题,请随时提问。

英文:

Basically I'm building a simple login app for JavaScript using an API. I get a 200 ok from the API and in the response I get all the posts, what I'm trying to do is to match the user-input with one of the posts in order to login. Do I have to iterate through everyone? Spontaneously feel that it would be bad for performance. So how should I proceed in order to make the code in the best way possible? Below is my JavaScript Code and HTML code.

async function login() {
    const username = document.getElementById(&quot;username&quot;).value;
    const password = document.getElementById(&quot;password&quot;).value;
    const users = &#39;http://webbred2.utb.hb.se/~fewe/api/api.php?data=students&#39;;
  
    try {
      const response = await fetch(users, {
        method: &quot;POST&quot;,
        body: JSON.stringify({ 
          username: username, 
          password: password 
        })
      });
  
      const data = await response.json();

      // Loop through the data to find a match with the user input
      let authenticated = false;  
      for(let user of users){
        if (user.username === username &amp;&amp; user.password === password){
            authenticated = true;
        window.location.href = &quot;quiz.html&quot;; 
    }
    else 
    {
        // login failed
        document.getElementById(&quot;message&quot;).innerHTML = &quot;Incorrect username or password&quot;;
    }
}
    } catch (error) {
      console.error(error);
      document.getElementById(&quot;message&quot;).innerHTML = &quot;An error occurred&quot;;
    }
  }

HTML code

&lt;!DOCTYPE html&gt;

&lt;html lang=&quot;sv&quot; dir=&quot;ltr&quot;&gt;
&lt;head&gt;
  &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;
  &lt;meta charset=&quot;utf-8&quot;&gt;
  &lt;link rel=&quot;stylesheet&quot; href=&quot;style.css&quot;&gt;
  &lt;title&gt;Login Kurs&#246;versikt&lt;/title&gt;
  &lt;script src=&quot;index.js&quot;&gt;&lt;/script&gt;
&lt;/head&gt;

&lt;body&gt;
  &lt;div class=&quot;login&quot;&gt;
    &lt;h1&gt;Logga in h&#228;r f&#246;r kurs&#246;versikt!&lt;/h1&gt;
    &lt;label for=&quot;username&quot;&gt;Username:&lt;/label&gt;
    &lt;input type=&quot;text&quot; id=&quot;username&quot; name=&quot;username&quot;&gt;&lt;br&gt;&lt;br&gt;
    &lt;label for=&quot;password&quot;&gt;Password:&lt;/label&gt;
    &lt;input type=&quot;password&quot; id=&quot;password&quot; name=&quot;password&quot;&gt;&lt;br&gt;&lt;br&gt;
    &lt;input type=&quot;button&quot; value=&quot;Login&quot; onclick=&quot;login()&quot;&gt;
  &lt;/div&gt;
  &lt;p id=&quot;message&quot;&gt;&lt;/p&gt;
&lt;/body&gt;
&lt;/html&gt;

I'm trying to login in with credentials that a user inputs and match them towards the API-response so I get logged in.

答案1

得分: 1

Note

看起来你的服务器正在发送一个明文列表,其中包含系统中的所有密码。这不是一个好主意。你应该在服务器端进行密码检查,以便用户不会收到这些信息。最佳做法还是加密密码,以便它们不以明文存储。

Answer

除此之外,加快查找的一种方法是使用对象而不是数组。

有了用户列表,你需要使用for循环或users.find()来搜索用户。

const users = [
    {username: 'a', password: 'aa'},
    {username: 'b', password: 'bb'},
    {username: 'c', password: 'cc'},
];

使用对象,你可以直接使用userPasswords[username]来访问想要的用户。

const userPasswords = {
    a: 'aa',
    b: 'bb',
    c: 'cc',
};
英文:

Note

It looks like your server is sending a PLAINTEXT LIST OF EVERY PASSWORD IN THE SYSTEM. This is not a good idea. You should do the password checking on the server side so that the user does not get that information sent to them. The best practice would be to also encrypt the passwords so that they are not stored in plain text.

Answer

But aside from that, one way to do faster lookups is to use an object instead of an array.

With a list of users, you will need to search for the user using a for loop or users.find().

const users = [
    {username: &#39;a&#39;, password: &#39;aa&#39;},
    {username: &#39;b&#39;, password: &#39;bb&#39;},
    {username: &#39;c&#39;, password: &#39;cc&#39;},
];

With an object, you can go directly to the user you want using userPasswords[username].

const userPasswords = {
    a: &#39;aa&#39;,
    b: &#39;bb&#39;,
    c: &#39;cc&#39;,
};

huangapple
  • 本文由 发表于 2023年3月7日 03:01:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/75654799.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定