支配vue框架初階項目之博客網站-註冊功能

  • ArthurSloghtml

  • SLog-26前端

  • Year·1vue

  • Guangzhou·Chinanode

  • July 28th 2018mysql

關注微信公衆號「ArthurSlog」
微信掃描二維碼,關注個人公衆號

勿讓時光蹉跎,最寶貴的時間就是20幾歲,這個時候的你能承受住一輩子中最大的風險,有着能夠窮盡一博的底氣,勿讓時光蹉跎git


開發環境MacOS(High Sierra 10.13.5)

須要的信息和信息源:

開始編碼

  • 首先,安裝homebrow這個工具來協助咱們 (若是已經安裝brow就跳過這一步)

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"github

  • 使用brew安裝mysql (若是已經安裝mysql就跳過這一步)

brew install mysqlweb

  • 啓動mysql,檢查mysql是否完整安裝

mysql.server startsql

  • Starting MySQL數據庫

  • .SUCCESS!

  • 配置Mysql,設置root帳戶的密碼爲8個8

mysqladmin -u root password 88888888

  • 登錄數據庫

mysql -u root -p

  • 輸入密碼,再按enter鍵,命令行會變成如下狀態

mysql>

  • 輸入SQL命令,按enter鍵執行,列出已有的數據庫

mysql> show databases;

Database
information_schema
mysql
performance_schema
sys

4 rows in set(0.01 sec)

  • 咱們建立一個數據庫"my_db"

mysql> create database my_db;

Query OK, 1 row affected (0.02 sec)

  • 進入my_db數據庫

mysql> use my_db;

Database changed

  • 咱們建立一個新表「ArthurSlogAccount"
mysql> CREATE TABLE ArthurSlogAccount
(
ID int NOT NULL AUTO_INCREMENT,
AccountName varchar(255) NOT NULL,
Password varchar(255) NOT NULL,
Firstname varchar(255) NOT NULL,
Lastname varchar(255) NOT NULL,
Birthday varchar(255) NOT NULL,
Sex varchar(255) NOT NULL,
Age varchar(255) NOT NULL,
Wechart varchar(255) NOT NULL,
Qq varchar(255) NOT NULL,
Email varchar(255) NOT NULL,
Contury varchar(255) NOT NULL,
Address varchar(255) NOT NULL,
Phone varchar(255) NOT NULL,
Websize varchar(255) NOT NULL,
Github varchar(255) NOT NULL,
Bio varchar(255) NOT NULL,
PRIMARY KEY (ID)
);
複製代碼

Query OK, 0 rows affected (0.09 sec)

  • 向ArthurSlogAccount表裏插入一行數據
mysql> INSERT INTO ArthurSlogAccount (AccountName, Password, Firstname, Lastname, Birthday, Sex, Age, Wechart, Qq, Email, Contury, Address, Phone, Websize, Github, Bio)
VALUES ('ArthurSlog', 'ArthurSlog', 'a', 'xu', '2000/08/08', 'man', '18', 'ArthurSlog', '12345678888', '12345678888@qq.com', 'china', 'China/GuangZhou', '13666666666', 'https://github.com/BlessedChild', 'https://github.com/BlessedChild', 'This is mime ~');
複製代碼

Query OK, 1 row affected (0.08 sec)

  • 查看一下Account表

mysql> SELECT * FROM Account;

ID AccountName Password
1 ArthurSlog ArthurSlog

1 row in set (0.00 sec)

  • 退出mysql交互模式

exit;

Bye

  • 切換至項目路徑下

cd node_vue_directive_learningload

  • 接下來,咱們來完善一下注冊頁面 「signup.html」:

signup.html

<html>

<head>
    <meta charset="utf-8">
    <title>signin_ArthurSlog</title>
</head>

<body>

    <div>This is signin's page by ArthurSlog</div>
    <p>Singin</p>
    <form action="http://127.0.0.1:3000/singup" method="GET">
        Account: <br>
        <input type="text" name="name"> 
        <br>
        Password: <br>
        <input type="text" name="password">
        <br>
        Again Password: <br>
        <input type="text" name="repassword">
        <br>
        First Name: <br>
        <input type="text" name="firstname">
        <br>
        Last Name: <br>
        <input type="text" name="lastname">
        <br>
        Birthday: <br>
        <input type="text" name="birthday">
        <br>
        Sex: <br>
        <input type="text" name="sex">
        <br>
        Age: <br>
        <input type="text" name="age">
        <br>
        Wechart: <br>
        <input type="text" name="wechart">
        <br>
        QQ: <br>
        <input type="text" name="qq">
        <br>
        Email: <br>
        <input type="text" name="email">
        <br>
        Contury: <br>
        <input type="text" name="contury">
        <br>
        Address: <br>
        <input type="text" name="address">
        <br>
        Phone: <br>
        <input type="text" name="phone">
        <br>
        Websize: <br>
        <input type="text" name="websize">
        <br>
        Github: <br>
        <input type="text" name="github">
        <br>
        Bio: <br>
        <input type="text" name="bio">
        <br><br>
        <input type="submit" value="完成註冊">
    </form>
    <a href="./account.html">Signin</a>
    <br>
    <a href="./index.html">Return index's page</a>

</body>

</html>
複製代碼
  • 上面的代碼增長了用戶註冊模塊,關於表單
<form action="http://127.0.0.1:3000/singup" method="GET">
    Account: <br>
    <input type="text" name="name"> 
    <br>
    Password: <br>
    <input type="text" name="password">
    <br>
    Again Password: <br>
    <input type="text" name="repassword">
    <br>
    First Name: <br>
    <input type="text" name="firstname">
    <br>
    Last Name: <br>
    <input type="text" name="lastname">
    <br>
    Birthday: <br>
    <input type="text" name="birthday">
    <br>
    Sex: <br>
    <input type="text" name="sex">
    <br>
    Age: <br>
    <input type="text" name="age">
    <br>
    Wechart: <br>
    <input type="text" name="wechart">
    <br>
    QQ: <br>
    <input type="text" name="qq">
    <br>
    Email: <br>
    <input type="text" name="email">
    <br>
    Contury: <br>
    <input type="text" name="contury">
    <br>
    Address: <br>
    <input type="text" name="address">
    <br>
    Phone: <br>
    <input type="text" name="phone">
    <br>
    Websize: <br>
    <input type="text" name="websize">
    <br>
    Github: <br>
    <input type="text" name="github">
    <br>
    Bio: <br>
    <input type="text" name="bio">
    <br><br>
    <input type="submit" value="完成註冊">
</form>
複製代碼
  • 上面的代碼完成一個註冊信息的表單

  • 接下來咱們編寫後端對應的部分

index.js

const serve = require('koa-static');
const Koa = require('koa');
const app = new Koa();
const Router = require('koa-router');
const router = new Router();

// $ GET /package.json
app.use(serve('.'));

//登錄模塊 signin()
router.get('/signin', async (ctx) => {

    var mysql = require('mysql');
    var connection = mysql.createConnection({
        host: 'localhost',
        user: 'root',
        password: '88888888',
        database: 'my_db'
    });

    
    connection.connect(function (err) {
        if (err) {
            console.error('error connecting: ' + err.stack);
            return;
        }
        console.log('connected as id ' + connection.threadId);
    });
    

    var response = {
        "name": ctx.query.name,
        "password": ctx.query.password
    };

    var addSql = 'SELECT * FROM ArthurSlogAccount WHERE AccountName=?';
    var addSqlParams = [response.name];

    ctx.body = await new Promise((resolve, reject) => {

        connection.query(addSql, addSqlParams, function (err, result) {
            if (err) {
                reject(err);
                console.log('[SELECT ERROR] - ', err.message);
                return;
            }
            if (result[0].Password == response.password) {
                resolve(result[0]);
                console.log('Welcome~ SingIn Successul ^_^' + '\\' + 'Level: ' + result[0].Level + ' Houses: ' + result[0].Houses);
            }
            if (result[0].Password != response.password) {
                reject('SingIn Fault ^_^!');
                console.log('SingIn Fault ^_^!');
            }
        });
    });
    connection.end();
});

//註冊模塊 signup() 
router.get('/signup', async (ctx) => {

    var mysql = require('mysql');
    var connection = mysql.createConnection({
        host: 'localhost',
        user: 'root',
        password: '88888888',
        database: 'my_db'
    });

    
    connection.connect(function (err) {
        if (err) {
            console.error('error connecting: ' + err.stack);
            return;
        }
        console.log('connected as id ' + connection.threadId);
    });
    

    var response = {
        "name": ctx.query.name,
        "password": ctx.query.password,
        "firstname": ctx.query.firstname,
        "lastname": ctx.query.lastname,
        "birthday": ctx.query.birthday,
        "sex": ctx.query.sex,
        "age": ctx.query.age,
        "wechart": ctx.query.wechart,
        "qq": ctx.query.qq,
        "email": ctx.query.email,
        "contury": ctx.query.contury,
        "address": ctx.query.address,
        "phone": ctx.query.phone,
        "websize": ctx.query.websize,
        "github": ctx.query.github,
        "bio": ctx.query.bio
    };

    var  addSql = 'INSERT INTO ArthurSlogAccount(AccountName, Password, Firstname, Lastname, Birthday, Sex, Age, Wechart, Qq, Email, Contury, Address, Phone, Websize, Github, Bio) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)';
    var  addSqlParams = [response.name, response.password, response.firstname, response.lastname, response.birthday, response.sex, response.age, response.wechart, response.qq, response.email, response.contury, response.address, response.phone, response.websize, response.github, response.bio];



    ctx.body = await new Promise((resolve, reject) => {

        connection.query(addSql,addSqlParams,function (err, result) {
            if(err){
                reject(err);
                console.log('[INSERT ERROR] - ',err.message);
                return;
            }
            resolve('Singup Successful!');
        });
    });
    connection.end();
});

app.use(router.routes());

app.listen(3000);

console.log('listening on port 3000');

複製代碼
  • 在使用express框架的時候,express 用來傳值的是 req 和 res,req 就是從前端網頁傳過來的信息,而 res 就是咱們後端傳給前端的信息,這樣的設計是根據 http協議 決定的,其中

  • http_URL = "http:" "//" host [ ":" port ] [ abs_path [ "?" query ]] 這是http協議定義的URL協議標準

在express框架環境中

app.get('/signup', function (req, res) {
 
    var mysql      = require('mysql');
    var connection = mysql.createConnection({
      host     : 'localhost',
      user     : 'root',
      password : '88888888',
      database : 'my_db'
    });
     
    connection.connect();

    var response = {
        "name": ctx.query.name,
        "password": ctx.query.password,
        "firstname": ctx.query.firstname,
        "lastname": ctx.query.lastname,
        "birthday": ctx.query.birthday,
        "sex": ctx.query.sex,
        "age": ctx.query.age,
        "wechart": ctx.query.wechart,
        "qq": ctx.query.qq,
        "email": ctx.query.email,
        "contury": ctx.query.contury,
        "address": ctx.query.address,
        "phone": ctx.query.phone,
        "websize": ctx.query.websize,
        "github": ctx.query.github,
        "bio": ctx.query.bio
    };

    var  addSql = 'INSERT INTO ArthurSlogAccount(AccountName, Password, Firstname, Lastname, Birthday, Sex, Age, Wechart, Qq, Email, Contury, Address, Phone, Websize, Github, Bio) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)';
    var  addSqlParams = [response.name, response.password, response.firstname, response.lastname, response.birthday, response.sex, response.age, response.wechart, response.qq, response.email, response.contury, response.address, response.phone, response.websize, response.github, response.bio];

    connection.query(addSql,addSqlParams,function (err, result) {
        if(err){
            console.log('[INSERT ERROR] - ',err.message);
            res.send('執行sql出錯!');
            return;
        }
        res.send('Welcome~ SingUp Success ^_^');
    });

    connection.end();
 });
複製代碼
  • 關鍵的地方在於,koa框架 不一樣於 express框架,咱們須要讓頁面在數據庫命令執行完成後再進行渲染,以便咱們把從數據庫獲取到的值完整的傳給前端,因此咱們須要修改一下語法

  • 由於 mysql中間件 使用回調而不是承諾(promise),所以,要使用await來構建承諾(promise),以下面代碼同樣,它將等待承諾獲得解決或拒絕

註冊模塊 signup()

router.get('/signup', async (ctx) => {

    var mysql = require('mysql');
    var connection = mysql.createConnection({
        host: 'localhost',
        user: 'root',
        password: '88888888',
        database: 'my_db'
    });

    
    connection.connect(function (err) {
        if (err) {
            console.error('error connecting: ' + err.stack);
            return;
        }
        console.log('connected as id ' + connection.threadId);
    });
    

    var response = {
        "name": ctx.query.name,
        "password": ctx.query.password,
        "firstname": ctx.query.firstname,
        "lastname": ctx.query.lastname,
        "birthday": ctx.query.birthday,
        "sex": ctx.query.sex,
        "age": ctx.query.age,
        "wechart": ctx.query.wechart,
        "qq": ctx.query.qq,
        "email": ctx.query.email,
        "contury": ctx.query.contury,
        "address": ctx.query.address,
        "phone": ctx.query.phone,
        "websize": ctx.query.websize,
        "github": ctx.query.github,
        "bio": ctx.query.bio
    };

    var  addSql = 'INSERT INTO ArthurSlogAccount(AccountName, Password, Firstname, Lastname, Birthday, Sex, Age, Wechart, Qq, Email, Contury, Address, Phone, Websize, Github, Bio) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)';
    var  addSqlParams = [response.name, response.password, response.firstname, response.lastname, response.birthday, response.sex, response.age, response.wechart, response.qq, response.email, response.contury, response.address, response.phone, response.websize, response.github, response.bio];



    ctx.body = await new Promise((resolve, reject) => {

        connection.query(addSql,addSqlParams,function (err, result) {
            if(err){
                reject(err);
                console.log('[INSERT ERROR] - ',err.message);
                return;
            }
            resolve('Singup Successful!');
        });
    });
    connection.end();
});
複製代碼
  • koa 框架與 express 框架不一樣的地方還在於,koa 使用 「ctx」 代替了 express 框架的 「req」 和 「res」

  • 把 request 和 response 集合成一個 ctx,ctx對應了 req 和 res 的每一個屬性,參考 koa官方手冊

Request 別名

如下訪問器和 Request 別名等效:

ctx.header
ctx.headers
ctx.method
ctx.method=
ctx.url
ctx.url=
ctx.originalUrl
ctx.origin
ctx.href
ctx.path
ctx.path=
ctx.query
ctx.query=
ctx.querystring
ctx.querystring=
ctx.host
ctx.hostname
ctx.fresh
ctx.stale
ctx.socket
ctx.protocol
ctx.secure
ctx.ip
ctx.ips
ctx.subdomains
ctx.is()
ctx.accepts()
ctx.acceptsEncodings()
ctx.acceptsCharsets()
ctx.acceptsLanguages()
ctx.get()
複製代碼

Response 別名

如下訪問器和 Response 別名等效:

ctx.body
ctx.body=
ctx.status
ctx.status=
ctx.message
ctx.message=
ctx.length=
ctx.length
ctx.type=
ctx.type
ctx.headerSent
ctx.redirect()
ctx.attachment()
ctx.set()
ctx.append()
ctx.remove()
ctx.lastModified=
ctx.etag=
複製代碼
  • 例如,你須要獲取前端表單裏的 「name」 值:
var name = ctx.query.name;
複製代碼
  • 再舉個栗子,給前端返回一些數據:
ctx.body = 'Hello ArthurSlog~';
複製代碼

sudo npm install mysql koa-router

  • 你還能夠選擇 mysql2中間件,使用方法參考連接的官方手冊

  • ok,如今,啓動靜態web服務器

node index.js

  • 打開瀏覽器,在地址欄輸入 127.0.0.1:3000

  • 點擊 Signup 進入註冊界面

  • 輸入註冊信息以下:

Tap Values
Account ArthurSlog1
Password ArthurSlog1
Again Password ArthurSlog1
First Name A
Last Name Xu
Birthday 2008/08/08
Sex man
Age 10
Wechat ArthurSlog
QQ 12345678
Email 12345678@qq.com
Contury China
Address China/Guangzhou
Phone 12345678
Websize https://github.com/BlessedChild
Github https://github.com/BlessedChild
Bio This is mime~
  • 點擊註冊,提示註冊成功

  • 返回主頁,點擊 Signin 進入登錄界面

  • 輸入剛剛註冊的帳戶和密碼,而後點擊登錄,成功返回 JSON 字符串:

{"ID":2,"AccountName":"ArthurSlog1","Password":"ArthurSlog1","Firstname":"a","Lastname":"xu","Birthday":"2008/08/08","Sex":"man","Age":"10","Wechart":"ArthurSlog","Qq":"12345678","Email":"12345678@qq.com","Contury":"China","Address":"China/GUangzhou","Phone":"12345678","Websize":"https://github.com/BlessedChild","Github":"https://github.com/BlessedChild","Bio":"This is mime~"}
複製代碼
  • 至此,咱們完成了前端的註冊功能和後端的註冊模塊。

歡迎關注個人微信公衆號 ArthurSlog

ArthurSlog
微信掃描二維碼,關注個人公衆號

若是你喜歡個人文章 歡迎點贊 留言

謝謝

相關文章
相關標籤/搜索