Vue.js is a popular JavaScript framework that provides many features for building user interfaces and single-page applications. Vue.js also provides JavaScript developers with many options to make it easier to communicate with backend servers. In this article, we will learn how to use Vue.js, combined with a SQL database, to implement login and registration functions, and provide corresponding SQL statements.
When implementing the login function in Vue.js, you need to pay attention to the following aspects:
The following is a code example to implement the Vue.js login function, which uses the MySQL database.
app.post('/register',function(req,res){
const {username, password} = req.body const sql = 'insert into users (username,password) values (?,?)' connection.query(sql,[username,password],(err,result)=>{ if(err){ console.log(err) res.send({ code:1, msg:'用户名已存在!' }) }else{ res.send({ code:0, msg:'注册成功!' }) } })
})
app.post('/login',function(req,res){
const {username, password} = req.body const sql = 'select * from users where username=? and password=?' connection.query(sql,[username,password],(err,result)=>{ if(err){ console.log(err) } if(result.length===0){ res.send({ code:1, msg:'用户名或密码错误!' }) }else{ const userInfo = JSON.stringify({ id:result[0].id, username:result[0].username }) res.send({ code:0, msg:'登录成功', userInfo }) } })
})
In the above code, we define two routes by using the express framework: one with for registration and another for login. In the post request, we get the username and password from req.body and send them to the database for verification. If the verification is successful, we store the user information in the userInfo object and send it back to the frontend.
It should be noted that when using Vue.js, we usually store user information in the browser's local storage and use it in future sessions. Here is a simple example that demonstrates how to store user information in localStorage:
localStorage.setItem('userInfo', JSON.stringify(userInfo))
localStorage.getItem('userInfo')
In short, Vue.js is a powerful framework that can be easily integrated with a SQL database, thus Implement common login and registration functions. The above code example demonstrates how to authenticate using Vue.js and MySQL and store it in the browser's local storage. Hope this article is helpful to you!
The above is the detailed content of How to write vue login registration sql statement. For more information, please follow other related articles on the PHP Chinese website!