Original connection
Get ready
Before you start doing this, hopefully you've configured the node,express and MySQL development environment. You can also refer to the reference article
Configuration of the development environment
- New Project
Refer to the installation and new project for Mac Down Express
- MySQL Module
package.json
dependencies
Add the following code "mysql": "latest",
to the file
The final effect:
Then cd
go to the directory where the project is located, execute it in the terminal npm install
, and the project will configure the MySQL module.
- New Database configuration file
Create a new directory under the project directory db
, create a new two files in the catalog entry, DBConfig.js
and usersql.js
The effect is as follows:
DBConfig.js
Here is the configuration file for the database, as long as the code is as follows:
module.exports ={ mysql: { ‘root‘, ‘123456‘, ‘userinfo‘ }};
Is the user name, password, and database name of the database. If your database and code are no longer a computer, you need the address of the database.
usersql.js
Is the MySQL operation statement needed to implement the background business
var UserSQL = { insert:‘INSERT INTO user(username,password,date,type,openid) VALUES(?,?,?,?,?)‘, bangding:‘UPDATE user SET type = ?,openid = ? WHERE username = ? AND password = ? ‘, queryAll:‘SELECT * FROM user‘, getUserByOpenid:‘SELECT * FROM user WHERE openid = ? ‘, getUserByInfo:‘SELECT * FROM user WHERE username = ? AND password = ? ‘, deleteUserByInfo:‘DELETE FROM user WHERE username = ? AND password = ? ‘,};module.exports = UserSQL;
Enabling background Business
- Business process
Before doing business or looking at the process, I drew a simple process for us to log in and bind third parties after using the app. The registration process is also simplified.
I also simplified the registration, that is, to enter the account number and password can be registered.
- Code implementation
My specific business is written in users.js
The premise is that the corresponding databases and tables have been established.
The first step is to introduce MySQL dependency
// 导入MySQL模块varrequire(‘../db/DBConfig‘);varrequire(‘../db/usersql‘);varrequire(‘mysql‘// 引入mysql依赖var// 建立连接
- First look at the registration process:
1. The user enters the user name and the password, clicks the registration button, sends the registration request;
2. Background based on user submitted user name and password to go to the data area to find there are no corresponding users,
- No, registration is successful, insert new user into database and record registration time
- There, registration failed, user already exists
//Register interfaceRouter.all ('/user/register ', function(req, res, next){ if(Req.method = ="POST") {varparam = req.body; }Else{varparam = Req.query | | Req.params; } client.query (User.getuserbyinfo,[param.username,param.password], function (err, results){ if(ERR) {ThrowERR}Else{//database does not exist for registration success if(Results.length = =0) {//Insert a new user into the databaseClient.query (User.insert,[param.username,param.password,getdatastr (),"',"'], function (err, results) { if(ERR) {ThrowERR}Else{Res.end (JSON. stringify ({status:' + ', msg:' registered successfully! '})); } }) }Else{//Database exists on registration failedRes.end (JSON. stringify ({status:' 101 ', msg:' The user name has been registered '})); } } })});
- Login process
Login is more user submitted by the user name and password to go to the data area comparison, the user name and password are the same log in, or prompt the user name or password error.
Of course this is simple, but also to do is whether there is a user.
//Login InterfaceRouter.all ('/user/login ', function(req, res, next){ if(Req.method = ="POST") {varparam = req.body; }Else{varparam = Req.query | | Req.params; } client.query (User.getuserbyinfo,[param.username,param.password], function (err, results){ if(ERR) {ThrowERR}Else{//Database exists if(Results.length = =0) {Res.end (JSON. stringify ({status:' 102 ', msg:' User name or password error '})); }Else{if(results[0].username = = Param.username && results[0].password = = Param.password) {res.end (JSON. stringify ({status:' + ', msg:' Login successful '})); } } } })});
- Third-party Login
There are two steps to a third-party login:
Based on the user's unique identification of third-party users, this is referred openid
to as database lookup
- One of the users of the database
openid
returns the registration success with this equality
- Database does not, jump to bound page, do the operation of binding user name
Here, for the foreground to be able to determine whether the user is bound, I gave a flag
field.
//third-party login interfaceRouter.all ('/user/thirdlogin ', function(req, res, next){ if(Req.method = ="POST") {varparam = req.body; }Else{varparam = Req.query | | Req.params; } console.log (Param.openid); Client.query (User.getuserbyopenid,[param.openid], function (err, results){ if(ERR) {ThrowERR}Else{//database does not exist on jump binding flag=1 need to bind flag=2//Do not need binding if(Results.length = =0) {Res.end (JSON. stringify ({status:' + ', msg:' Operation succeeded ', Flag:' 1 '})); }Else{//Database exists on login successRes.end (JSON. stringify ({status:' + ', msg:' Login successful ', Flag:' 2 '})); } } })});
- Bind user
This is nothing. is to update the user's data
//Binding interfaceRouter.all ('/user/bangding ', function(req, res, next){ if(Req.method = ="POST") {varparam = req.body; }Else{varparam = Req.query | | Req.params; } client.query (User.getuserbyinfo,[param.username,param.password], function (err, results){ if(ERR) {ThrowERR}Else{//update user InformationClient.query (User.bangding,[param.type,param.openid,param.username,param.password], function (err, results) { if(ERR) {ThrowERR}Else{Res.end (JSON. stringify ({status:' + ', msg:' Bind succeeded! '})); } }) } })});
Test
The above process is basically the simplest.
The test can be tested in the browser and input the corresponding parameters according to the interface. I wrote a simple test app for myself.
I inserted some data in the database beforehand.
App Effects:
Summarize
It used to be an iOS app or H5 app. Write the front and back desk on your own this time. A little breakthrough.
When the front and back of the writing together, found before and after the platform, need a lot of cooperation. Before just the interface is not correct, look for background modification. This time it's your own amendment.
This requires a lot of co-ordination. Just like at the beginning of the month to do the Logistics Management app. The backstage staff I will not vomit the trough. I want to find him. Address user name and password for the database
Want to come over, I write backstage to forget.
To learn a lot, meet the problem do not be afraid, careful reading the wrong information, the first quiet to think, look at the document. Do not understand the Internet search.
Node.js+express+mysql Registration Login Binding Third Party Login