node.js 链接数据库实现vue与后端交互

首先实现vue前端的简单页面,本页面是采用vue@cli构建项目,项目实现简单的登录注册功能,利用express进行网络通信。

1:前端vue项目

设置vue.config.js:设置跨域相关(本身是在自己电脑上启动两个服务器一个后端服务器一个是vue启动的服务端口不同会造成跨域的问题)

module.exports = {
    publicPath: '/',
    devServer: {
        proxy: {
            '/api/login': {
                target: 'http://localhost:3000/login',
                changeOrigin: true,
                ws: true,
                pathRewrite: {
                  '^/api/login': ''
                }
            },
            '/api/register': {
                target: 'http://localhost:3000/register',
                changeOrigin: true,
                ws: true,
                pathRewrite: {
                  '^/api/register': ''
                }
            }
        }
    }
}

login.vue







2:服务端index.js

const express = require("express");
const crypto = require("crypto");
const bodyParser = require("body-parser");
const app = express();
const connection = require("../dao/index.js");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.get("/", (req,res) => {
    // 得到get请求的参数 使用query
    console.log(req.query);
    res.send("hello world dfasd");
});
app.get("/data",(req,res) => {
    // res.writeHead("Access-Control-Allow-Origin","*");
    res.setHeader("Access-Control-Allow-Origin","*");
    let data = {
        message: "hello",
        status: 200,
        data: {
            name: "lck",
            age: 34,
            sex: 0
        }
    }
    res.send(JSON.stringify(data));
});
app.post("/login",async (req,res,next) => {
    console.log("req is ",req.body);
    let username = req.body.username;
    let password = req.body.password;
    let self = this;
    let realPassword = Util.md5(Util.md5(password).substr(10,20) + Util.md5(password));
    console.log("realPassword is ",realPassword);
    try {
        const insertRes = await new Promise((resolve,reject) => {
            let addUser = "select * from user where username = ?";
            let queryParams = [username];
            connection.query(addUser,queryParams,(err,result) => {
                try {
                    console.log("result is ",result);
                    resolve(result);
                } catch(e) {
                    console.log("e is ",e);
                    reject();
                }
            })
        });
        if(insertRes.length > 0) {
            console.log("insertRes is ",insertRes[0]);
            console.log("insertRes is ",insertRes[0].password === realPassword);
            if(insertRes[0].password === realPassword) {
                res.send({message: "ok",status: 200});
            } else {
                res.send({message: "密码错误",status: 200});
            }
        } else {
            res.send({message: "用户名不存在",status: 400});
        }
    } catch(e) {
        console.log("e is ",e);
        res.send({message: "no",status: 400});
    }
});
app.post("/register",async (req,res,next) => {
    let hashes = crypto.getHashes();
    let keyhash = crypto.createHmac('md5',req.body.password)
                  .update('I love cupcakes')
                  .digest('hex');
    console.log("hashes is ",keyhash);
    let username = req.body.username;
    let password = req.body.password;
    try {
        const insertRes = await new Promise((resolve,reject) => {
            let addUser = `insert into user(id,username,password,gender) values(null,?,?,?)`;
            let addParams = [username,keyhash,1];
            connection.query(addUser,addParams,(err,result) => {
                console.log("result is ",result);
                resolve(result);
            })
        });
        res.send({message: "ok",status: 200});
    } catch(e) {
        res.send({message: "no",status: 400});
    }
})
let server = app.listen(3000,() => {
    let host = server.address().address;
    let port = server.address().port;
    console.info("host is ",host," port is ",port);
})

dao层index.js

const mysql = require("mysql");
const connection = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "密码",
    database: "数据库名"
});
connection.connect();
module.exports = connection;

这样只是简单的一些关于express,mysql的简单操作,在此记录下express使用的流程(接收post请求参数和链接数据库对数据库进行操作的具体细节)哪里不适还请各位大佬指正

你可能感兴趣的:(javaScript)