nodejs串連mysql資料庫及基本知識點詳解,nodejsmysql

來源:互聯網
上載者:User

nodejs串連mysql資料庫及基本知識點詳解,nodejsmysql

本文執行個體講述了nodejs串連mysql資料庫及基本知識點。分享給大家供大家參考,具體如下:

一、幾個常用的全域變數

1、__filename擷取當前檔案的路徑
2、__dirname擷取當前檔案的目錄
3、process.cwd()擷取當前工程的目錄

二、檔案的引入與匯出

1、使用require引入檔案

2、使用module.exports匯出檔案中指定的變數、方法、對象

三、node項目的搭建目錄結構

demo

    package.json 當前項目所依賴的包或者模組
    router  存放路由的檔案
    views   存放視圖的模組
    public  靜態檔案
    module 書寫模組比如資料庫
    app.js 主入口檔案

四、將路由視圖單獨寫在router檔案中demo

1、視圖視圖檔案

const express = require("express");const router = express.Router();router.get("/", (req, res) => { res.send("hello word");});router.get("/article", (req, res) => { res.send("我是文章列表");})module.exports = router;

2、在主檔案中調用

'use strict';const express = require("express");const app = express();app.use("/",require("./router/03_router"))app.use("/app",require("./router/03_router1"))app.listen(3000);

五、使用ejs模板

1、需要安裝但可以不引入

npm install ejs --save

2、在主檔案中配置

//配置模板的檔案路徑app.set("views",__dirname+"/views");//配置模板引擎app.set("view engine","ejs");

3、使用

①、模板檔案

<!doctype html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport"   content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title></head><body><h1>我是模板渲染的</h1></body></html>

②、在路由中渲染模板

'use strict';const express = require("express");const router = express.Router();router.get("/", (req, res) => { //可以直接使用res.render("03_index"); res.render("03_index.ejs");});router.get("/article", (req, res) => { res.send("我是文章列表");})module.exports = router;

③、主檔案

'use strict';const express = require("express");const app = express();//配置模板的檔案路徑app.set("views",__dirname+"/views");//配置模板引擎app.set("view engine","ejs");app.use("/",require("./router/03_router"))app.use("/app",require("./router/03_router1"))app.listen(3000);

六、關於ejs模板檔案的使用

1、返回資料

...let dataset = { name:"張三", age:20, books:['三國演義','西遊記','紅樓夢','水滸傳']}res.render("03_index.ejs",dataset);...

2、普通的欄位

<h2><%= name %></h2><h2><%= age %></h2>

3、迭代數組

<ul> <% for(let i in books){%>  <li><%= books[i] %></li> <%}%></ul>

七、載入靜態檔案

1、主檔案中配置

//設定靜態檔案的載入(js,css,img)app.use(express.static(__dirname+"/public"));

2、在模板中使用

<link rel="stylesheet" href="./css/bootstrap.css" rel="external nofollow" ><script type="text/javascript" src="./js/jquery-3.1.1.min.js"></script><img src="./img/002.jpg">...

八、使用mysql資料庫

1、在module中建立一個db.js的檔案

'use strict';const mysql = require("mysql");/** * 將整個方法全部暴漏出去 * @param sql sql語句 * @param arg 傳遞到sql語句中的參數,可以不寫 * @param callback 回呼函數,可以不寫 */module.exports = function (sql,arg,callback) { //1.建立串連(根據自己的資料庫配置) let config = mysql.createConnection({  host:"localhost", //資料庫的地址  user:"root", //資料庫使用者名稱  password:"root", //資料庫密碼  port:"3306", //mysql資料庫的連接埠號碼  database:"mybatistest" //使用那個資料庫 }); //2.開始串連資料庫 config.connect(); //3.對資料庫的增刪改查操作 config.query(sql,arg,(err,data)=>{  callback && callback(err,data); }) //4.關閉資料庫 config.end();}

2、在router視圖中使用查詢資料

①、引入檔案

//引入資料庫檔案const db = require("./../module/db");

②、視圖中使用

router.get("/", (req, res) => { db("select * from m_dept",(err,data)=>{  console.log(data);  res.render("03_index.ejs",{data:data}); })});

3、新增資料

①、前端頁面見代碼案例

②、通過req.query擷取使用者資料參數

router.get("/regist",(req, res)=>{ //擷取到輸入參數,前提是input上要寫name console.log(req.query); db("insert into student(name,age) values(?,?)",[req.query.username,req.query.age],(err,data)=>{  console.log(data);  if(data){   res.send("成功");  } })})

九、關於node返回json的方式

在前後端分離開發模式中後端返回的資料一般都是json,不需要使用ejs模板引擎了

...res.json({ info:"成功", code:1});...

十、github上的本章節代碼案例https://github.com/kuangshp/node-pro1

希望本文所述對大家nodejs程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.