简体   繁体   中英

how to get token (at login) in nuxt App using my own backend api?

I'm working on a project with an other person. I'm doing the backend part and he's doing the frontend part.

Our users can register and login but we can't get the token that I generate in my back api.

I tried to found some sources to do that but nothing seems to be appropriate to our situation

How can we do that?

Thanks :)

Front:

    <form @submit.prevent="login" method="post">
      <div class="group_field">
        <input id="email" v-model="email" type="email" name="email" required>
        <label for="email">Email</label>
      </div>
      <div class="group_field">
        <input id="password" v-model="pswd" type="password" name="password" required>
        <label for="password">Password</label>
      </div>
      <button type="submit">
        Login
      </button>
      <small>Pas de compte ? <nuxt-link to="/register">S'inscrire</nuxt-link></small>
    </form>

<script>
export default {

  data () {
    return {
      email: '',
      pswd: '',
      token: '',
      error: null
    }
  },

  methods: {
    async login () {
      try {
        await this.$axios.post('http://localhost:3080/login', {
          email: this.email,
          pswd: this.pswd,
          token: this.token
        })

        this.$router.push('/')
      } catch (e) {
        this.error = e.response.data.message
      }
    }
  }

}
</script>

Back :

index.js :

router.route('/login')
        .post(logger, userController.logUser);

users.js :

export const logUser = async (req, res) => {
    if (!req.body.email || !req.body.pswd) return throwBadRequest('Missing parameters', res);
    if (!await utils.validateEmail(req.body.email)) return throwBadRequest('Wrong email format', res);
    if (!await utils.validatePassword(req.body.pswd)) return throwBadRequest('Wrong password formatmust be: at least 3 char long with 1 uppercase 1 lowercase and 1 number', res);
    await UserModel.fetchUser(req.body.email, req.body.pswd, (err, result) => {
        if (err) return throwIntServerError(err, res);
        req.token = { token: result };
        return sendOKWithData({ auth: true, token: result }, res);
    });
}

userModel.js :

UserSchema.statics.fetchUser = async function (userEmail, userPswd, cb) {
    await this.findOne({ userEmail }, async (err, user) => {
        if (err) return cb(err);
        if(!user) return cb(new Error('user Not Found'));
        const isValid = await bcrypt.compare(userPswd, user.userPswd);
        if(isValid === true) {
            let token = jwt.sign({ userEmail: userEmail, userPswd: userPswd }, secret, {expiresIn: 86400});
            return cb(null, token);
        } else {
            return null;
        }
    });
}

I personally use Nuxt auth to login and register users. It is convenient because the main configuration is set in nuxt.config.js. Using axios we have dedicated functions built into Nuxt Auth. Maybe I didn't help centrally with the problem, but maybe I pointed out an additional way out.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM