I want to create a login with a cookie and check the database if I am logged in, but the cookie is not created, I don't know where I went wrong

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

I want to create a login with a cookie and check the database if I am logged in, but the cookie is not created, I don't know where I went wrong

问题

我是编程新手,不知道如何使用cookie和本地json数据库完成登录。但我觉得我走在正确的方向上。在此提前感谢您的帮助。

这是我的本地json数据库db.js:

{
    "users": [
      {
        "username": "Trpimir",
        "email": "ttom@gmail.com",
        "password": "Password123",
        "id": 1
      },
      {
        "username": "user2",
        "email": "user1@gmail.com",
        "password": "user12345",
        "id": 2
      }
    ]
}

这是我的登录组件:

<script setup>
import { ref, onMounted } from 'vue'
import VueCookies from 'vue-cookies'
import axios from 'axios';

const LogInModalVisible = ref(false)

var baseURL = 'http://localhost:3000/'
var userURL = baseURL + "users";

let users = ref(null)
let username = ref(null)
let email = ref(null)
let password = ref(null)
let login = ref(true)
let signup = ref(true)

let usernameError = ref(null)
let emailError = ref(null)
let passwordError =ref(null)
let passwordValidation = ref(false)
let signupvalidation = ref(false)


onMounted(async () => {
    try {
            const res = await axios.get(baseURL + 'users');
            users = res.data;
            /* console.log(users) */

            /* loginSubmit() */
        } catch (e) {
            console.error(e)
        }
  })

async function loginSubmit()
{
    if(email.lenght == 0)
    {
        this.emailError = "Field is empty";
    }
    else
    {
        this.emailError = null
    }

    if(password.length == 0)
    {
        this.passwordError = "Field is empty!";
    }
    else if(password.length>0 && password.length<8)
    { 
        this.passwordError = "Password is too short!"
    }
    else
    {
        this.passwordError = null
    }

    /* const res = await axios.get(userURL);
    this.users = res.data; */

   for (var i = 0; i <users.length; i++)
            {
                if (this.users[i].email == this.email.value)
                {
                    if (this.users[i].password == this.password.value)
                    {
                        this.passwordValidation = true;
                        VueCookies.set('username', this.users[i].username, "120min");
                        VueCookies.set('email', this.email.value, "120min");
                        VueCookies.set('password', this.password.value, "120min");
                        VueCookies.set('id', this.users[i].id, "120min");

                        window.location.href = '/';
                        alert("Login successful");
                    }
                }
             }
             if(this.passwordValidation == false){ this.passwordError = "Incorrect password or username!"}
        }

</script>

<template>
    <div v-if="login">
        <el-dialog v-model="LogInModalVisible" title="LogIn" width="50%" height="50%" center>
            <el-form label-position='top' status-icon :label-width="80">

                <el-form-item label="Email">
                    <el-input type="email" id='email' aria-placeholder="Enter Email" v-model="email" />
                    <div class="input-message" v-if="emailError">
                        <h6>{{emailError}}</h6>
                    </div>
                </el-form-item>

                <el-form-item label="Password">
                    <el-input type="password" id='password' aria-placeholder="Enter Password" v-model="password" />

                    <div class="input-message" v-if="passwordError">
                        <h6>{{passwordError}}</h6>
                    </div>
                </el-form-item>
            </el-form>
            <div class="footer">
                <span>
                    <el-button @click="LogInModalVisible = false">Cancel</el-button>
                    <el-button type="primary" @click="LogInModalVisible = false; loginSubmit()">
                        LogIn
                    </el-button>
                </span>
                <div class="linkDiv">
                <p>Not a member?</p>
                <el-link type="primary" @click='login = false'>Sign-up now!</el-link>
            </div>
        </div>
        </el-dialog>
    </div>

    <div v-else>
        <el-dialog v-model="LogInModalVisible" title="SignUp" width="50%" height="50%" center>
            <el-form lebel-position='top' status-icon :label-width="80">

                <el-form-item label="Username">
                    <el-input type="text" id="username" aria-placeholder="Enter Username" v-model="username" />
                    <div class="input-message" v-if="usernameError">
                        <h6>{{ usernameError }}</h6>
                    </div>
                </el-form-item>

                <el-form-item label="Email">
                    <el-input type="email" id="email" aria-placeholder="Enter Email" v-model="email" />
                    <div class="input-message" v-if="emailError">
                        <h6>{{ emailError }}</h6>
                    </div>
                </el-form-item>

                <el-form-item label="Password">
                    <el-input type="password" id="password" aria-placeholder="Enter Password" v-model="password" />
                    <div class="input-message" v-if="passwordError">
                        <h6>{{ passwordError }}</h6>
                    </div>
                </el-form-item>
            </el-form>
            <div class="footer">
                <span class="dialog-footer">
                    <el-button @click="LogInModalVisible = false">Cancel</el-button>
                    <el-button type="primary" @click="LogInModalVisible = false">
                        SignUp
                    </el-button>
                </span>
                <div class="linkDiv">
                <p>Already a member?</p>
                <el-link type="primary" @click='login = true'>Log-In now!</el-link>
            </div>
        </div>
        </el-dialog>
    </div>
</template>

<style scoped>
.linkDiv{
    padding-top: 15px;
}
p {
    padding-bottom: 10px;
}
.footer{
    text-align: center;
    padding-top: 10px;
}
</style>
英文:

I'm new to programming and I don't know how to complete this login with cookie and local json database, but I think I'm on the right track. Thanks in advance for your help.

This is my local json database db.js:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

{
&quot;users&quot;: [
{
&quot;username&quot;: &quot;Trpimir&quot;,
&quot;email&quot;: &quot;ttom@gmail.com&quot;,
&quot;password&quot;: &quot;Password123&quot;,
&quot;id&quot;: 1
},
{
&quot;username&quot;: &quot;user2&quot;,
&quot;email&quot;: &quot;user1@gmail.com&quot;,
&quot;password&quot;: &quot;user12345&quot;,
&quot;id&quot;: 2
}
]
}

<!-- end snippet -->

This is my login component:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

&lt;script setup&gt;
import { ref, onMounted } from &#39;vue&#39;
import VueCookies from &#39;vue-cookies&#39;
import axios from &#39;axios&#39;;
const LogInModalVisible = ref(false)
var baseURL = &#39;http://localhost:3000/&#39;
var userURL = baseURL + &quot;users&quot;;
let users = ref(null)
let username = ref(null)
let email = ref(null)
let password = ref(null)
let login = ref(true)
let signup = ref(true)
let usernameError = ref(null)
let emailError = ref(null)
let passwordError =ref(null)
let passwordValidation = ref(false)
let signupvalidation = ref(false)
onMounted(async () =&gt; {
try {
const res = await axios.get(baseURL + &#39;users&#39;);
users = res.data;
/* console.log(users) */
/* loginSubmit() */
} catch (e) {
console.error(e)
}
})
async function loginSubmit()
{
if(email.lenght == 0)
{
this.emailError = &quot;Field is empty&quot;
}
else
{
this.emailError = null
}
if(password.length == 0)
{
this.passwordError = &quot;Field is empty!&quot;;
}
else if(password.length&gt;0 &amp;&amp; password.length&lt;8)
{ 
this.passwordError = &quot;Password is too short!&quot;
}
else
{
this.passwordError = null
}
/* const res = await axios.get(userURL);
this.users = res.data; */
for (var i = 0; i &lt;users.length; i++)
{
if (this.users[i].email == this.email.value)
{
if (this.users[i].password == this.password.value)
{
this.passwordValidation = true;
VueCookies.set(&#39;username&#39;, this.users[i].username, &quot;120min&quot;);
VueCookies.set(&#39;email&#39;, this.email.value, &quot;120min&quot;);
VueCookies.set(&#39;password&#39;, this.password.value, &quot;120min&quot;);
VueCookies.set(&#39;id&#39;, this.users[i].id, &quot;120min&quot;);
window.location.href = &#39;/&#39;;
alert(&quot;Login successful&quot;);
}
}
}
if(this.passwordValidation == false){ this.passwordError = &quot;Inccorect password or username!&quot;}
}
&lt;/script&gt;
&lt;template&gt;
&lt;div v-if=&quot;login&quot;&gt;
&lt;el-dialog v-model=&quot;LogInModalVisible&quot; title=&quot;LogIn&quot; width=&quot;50%&quot; height=&quot;50%&quot; center&gt;
&lt;el-form label-position=&#39;top&#39; status-icon :label-width=&quot;80&quot;&gt;
&lt;el-form-item label=&quot;Email&quot;&gt;
&lt;el-input type=&quot;email&quot; id=&#39;email&#39; aria-placeholder=&quot;Enter Email&quot; v-model=&quot;email&quot; /&gt;
&lt;div class=&quot;input-message&quot; v-if=&quot;emailError&quot;&gt;
&lt;h6&gt;{{emailError}}&lt;/h6&gt;
&lt;/div&gt;
&lt;/el-form-item&gt;
&lt;el-form-item label=&quot;Password&quot;&gt;
&lt;el-input type=&quot;password&quot; id=&#39;password&#39; aria-placeholder=&quot;Enter Password&quot; v-model=&quot;password&quot; /&gt;
&lt;div class=&quot;input-message&quot; v-if=&quot;passwordError&quot;&gt;
&lt;h6&gt;{{passwordError}}&lt;/h6&gt;
&lt;/div&gt;
&lt;/el-form-item&gt;
&lt;/el-form&gt;
&lt;div class=&quot;footer&quot;&gt;
&lt;span&gt;
&lt;el-button @click=&quot;LogInModalVisible = false&quot;&gt;Cancel&lt;/el-button&gt;
&lt;el-button type=&quot;primary&quot; @click=&quot;LogInModalVisible = false; loginSubmit()&quot;&gt;
LogIn
&lt;/el-button&gt;
&lt;/span&gt;
&lt;div class=&quot;linkDiv&quot;&gt;
&lt;p&gt;Not a member?&lt;/p&gt;
&lt;el-link type=&quot;primary&quot; @click=&#39;login =  false&#39;&gt;Sign-up now!&lt;/el-link&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/el-dialog&gt;
&lt;/div&gt;
&lt;div v-else&gt;
&lt;el-dialog v-model=&quot;LogInModalVisible&quot; title=&quot;SignUp&quot; width=&quot;50%&quot; height=&quot;50%&quot; center&gt;
&lt;el-form lebel-position=&#39;top&#39; status-icon :label-width=&quot;80&quot;&gt;
&lt;el-form-item label=&quot;Username&quot;&gt;
&lt;el-input type=&quot;text&quot; id=&quot;username&quot; aria-placeholder=&quot;Enter Username&quot; v-model=&quot;username&quot; /&gt;
&lt;div class=&quot;input-message&quot; v-if=&quot;usernameError&quot;&gt;
&lt;h6&gt;{{ usernameError }}&lt;/h6&gt;
&lt;/div&gt;
&lt;/el-form-item&gt;
&lt;el-form-item label=&quot;Email&quot;&gt;
&lt;el-input type=&quot;email&quot; id=&quot;email&quot; aria-placeholder=&quot;Enter Email&quot; v-model=&quot;email&quot; /&gt;
&lt;div class=&quot;input-message&quot; v-if=&quot;emailError&quot;&gt;
&lt;h6&gt;{{ emailError }}&lt;/h6&gt;
&lt;/div&gt;
&lt;/el-form-item&gt;
&lt;el-form-item label=&quot;Password&quot;&gt;
&lt;el-input type=&quot;password&quot; id=&quot;password&quot; aria-placeholder=&quot;Enter Password&quot; v-model=&quot;password&quot; /&gt;
&lt;div class=&quot;input-message&quot; v-if=&quot;passwordError&quot;&gt;
&lt;h6&gt;{{ passwordError }}&lt;/h6&gt;
&lt;/div&gt;
&lt;/el-form-item&gt;
&lt;/el-form&gt;
&lt;div class=&quot;footer&quot;&gt;
&lt;span class=&quot;dialog-footer&quot;&gt;
&lt;el-button @click=&quot;LogInModalVisible = false&quot;&gt;Cancel&lt;/el-button&gt;
&lt;el-button type=&quot;primary&quot; @click=&quot;LogInModalVisible = false&quot;&gt;
SignUp
&lt;/el-button&gt;
&lt;/span&gt;
&lt;div class=&quot;linkDiv&quot;&gt;
&lt;p&gt;Already a member?&lt;/p&gt;
&lt;el-link type=&quot;primary&quot; @click=&#39;login =  true&#39;&gt;Log-In now!&lt;/el-link&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/el-dialog&gt;
&lt;/div&gt;
&lt;/template&gt;
&lt;style scoped&gt;
.linkDiv{
padding-top: 15px;
}
p {
padding-bottom: 10px;
}
.footer{
text-align: center;
padding-top: 10px;
}
&lt;/style&gt;

<!-- end snippet -->

I think I've done most of it and I don't have any errors, just the cookie is not created

答案1

得分: 1

  1. 在Vue3中,您不需要使用 this,来为 ref 赋值或从 ref 读取值,请使用

  2. 我不确定您试图做什么,但是在数据库中循环遍历用户的值来匹配用户名和密码不是一个好主意,而且在 cookie 中设置密码也不是一个好主意。

  3. 尽管如此,只是为了解决您的 cookie 问题。我注释掉了不相关的部分并尝试了它,它完美地运行了。我还删除了 for 循环...

async function loginSubmit() {
      // if (email.value.length == 0) {
      //   emailError.value = "Field is empty";
      // } else {
      //   emailError.value = null;
      // }
    
      // if (password.value.length == 0) {
      //   passwordError.value = "Field is empty!";
      // } else if (password.value.length > 0 && password.value.length < 8) {
      //   passwordError.value = "Password is too short!";
      // } else {
      //   passwordError.value = null;
      // }
    
      if (users.value[0].email === email.value) {
        if (users.value[0].password == password.value) {
          console.log("Login successful");
          VueCookies.set("username", users.value[0].username, "120min");
          VueCookies.set("email", email.value, "120min");
          VueCookies.set("password", password.value, "120min");
          VueCookies.set("id", users.value[0].id, "120min");
    
          window.location.href = "/";
          alert("Login successful");
        }
      }
      if (this.passwordValidation == false) {
        this.passwordError = "Incorrect password or username!";
      }
    }

该 cookie 被设置而没有任何问题。

  1. 由于您是初学者,我建议一次解决一个问题。例如,测试是否获取了用户...然后进行用户登录和验证,然后设置 cookie,最后处理多个用户。这样更容易跟踪。

  2. 也建议当您在 StackOverflow 等地寻求帮助时,发布一个可工作的示例,这样人们可以查看代码并提供帮助。您可以使用像 stackblitz 等网站在云端复制您的 Vue 应用程序。

英文:
  1. You don't need to use this in vue3. to assign a value to ref or to read a value from ref use

  2. I am not sure what you are trying to do, but looping through users value in the database to match user name and password is not a good idea, and also it is not a good idea to set the password in the cookie.

  3. Nevertheless Just to address your cookie issue. i commented out non-relevant sections and tried it and it works perfectly. i also removed the for loop..

async function loginSubmit() {
// if (email.value.length == 0) {
//   emailError.value = &quot;Field is empty&quot;;
// } else {
//   emailError.value = null;
// }
// if (password.value.length == 0) {
//   passwordError.value = &quot;Field is empty!&quot;;
// } else if (password.value.length &gt; 0 &amp;&amp; password.value.length &lt; 8) {
//   passwordError.value = &quot;Password is too short!&quot;;
// } else {
//   passwordError.value = null;
// }
if (users.value[0].email === email.value) {
if (users.value[0].password == password.value) {
console.log(&quot;Login successful&quot;);
VueCookies.set(&quot;username&quot;, users.value[0].username, &quot;120min&quot;);
VueCookies.set(&quot;email&quot;, email.value, &quot;120min&quot;);
VueCookies.set(&quot;password&quot;, password.value, &quot;120min&quot;);
VueCookies.set(&quot;id&quot;, users.value[0].id, &quot;120min&quot;);
window.location.href = &quot;/&quot;;
alert(&quot;Login successful&quot;);
}
}
if (this.passwordValidation == false) {
this.passwordError = &quot;Inccorect password or username!&quot;;
}
}

The cookie was set without any issues.

I want to create a login with a cookie and check the database if I am logged in, but the cookie is not created, I don't know where I went wrong

  1. Since you are beginner i would suggest to tackle issues one by one. i.e test if user is fetched...then make a user login and validate it and then set cookie and then handle for multiple users. it will be easier to track.

  2. It is also recommended that when you seek help in stackoverflow etc, you post a working example, so that people can look at the code and help. You can use sites like stackblitz etc to replicate your vue app on the cloud.

huangapple
  • 本文由 发表于 2023年2月10日 16:37:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/75408656.html
匿名

发表评论

匿名网友

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

确定