[英]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.我们的用户可以注册和登录,但我们无法获得我在后台 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 :索引.js:
router.route('/login')
.post(logger, userController.logUser);
users.js :用户.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 :用户模型.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.我个人使用 Nuxt auth 登录和注册用户。 It is convenient because the main configuration is set in nuxt.config.js.很方便,因为主要的配置是在nuxt.config.js里面设置的。 Using axios we have dedicated functions built into Nuxt Auth.使用 axios,我们在 Nuxt Auth 中内置了专用功能。 Maybe I didn't help centrally with the problem, but maybe I pointed out an additional way out.也许我没有集中帮助解决这个问题,但也许我指出了一个额外的出路。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.