最新要闻

广告

手机

iphone11大小尺寸是多少?苹果iPhone11和iPhone13的区别是什么?

iphone11大小尺寸是多少?苹果iPhone11和iPhone13的区别是什么?

警方通报辅警执法直播中被撞飞:犯罪嫌疑人已投案

警方通报辅警执法直播中被撞飞:犯罪嫌疑人已投案

家电

全球简讯:express学会CRUD

来源:博客园


(相关资料图)

使用express 搭建项目

1==> express 项目名 -e2==> 然后按照提示就可以了cd 项目名3==>进入项目 下载依赖cnpm i 4==>启动项目nodemon app.js5==> 添加监听端口在app.js 中 在(module.exports = app;前添加)就是在第40行 添加如下,监听端口app.listen(666, () => {    console.log("后端服务器启动成功,地址是: http://127.0.0.1:666")})

下载mysql模块并连接数据库

应为我们要实现crud。所以我们需要与数据库相连接。因为我们要下载mysql模块连接数据库。第1步:下载模块 cnpm install mysql第2步  创建connectmysql.js文件,连接mysql。connectmysql.js文件代码如下const mysql=require("mysql");const connection=mysql.createConnection({    host:"localhost",  //默认链接的是本地    user:"root",       //用户名    password:"root",  //密码    database:"xuexishopsystem"  //链接的是哪个数据库})// 下面是测试数据库是否链接成功connection.query("select 1", (err, data) => {    if (err) {        console.log("报错了",err)    } else {        console.log("ok",data)    }})// 因为别人要用connection ,所以我要将它暴露出去哦module.exports=connection;第3步 执行 node connectmysql.js 看看是否链接成功

实现后端路由

在routes文件夹中新增一个文件。accounts.js文件这个文件是实现对账号的增加删除更改查询的。accounts.js 文件代码如下:var express = require("express");var router = express.Router();// 引入连接数据库的模块const connection=require("./connectmysql.js")/* GET users listing. */router.get("/", function(req, res, next) {  res.send("respond with a resource");});module.exports = router;

在app.js中去使用路由

var accountsRouter = require("./routes/accounts"); //引入路由// /accounts 是路由的前缀app.use("/accounts", accountsRouter);  //使用路由

cors 处理跨域

安装 cnpm install corsconst cors = require("cors")//在调用路由之前解决跨域app.use(cors())app.use("/", indexRouter);app.use("/users", usersRouter);app.use("/accounts", accountsRouter);

前端访问

前端输入: http://127.0.0.1:666/accounts get请求就可以输出respond with a resource

数据库的设计

数据库名称 smsm表名 account建表名的SQL命令create table account (    id int primary key auto_increment,    username varchar(30),    password varchar(30),    usergroup varchar(30),    ctime timestamp default current_timestamp)

在cmd中去连接数据库

mysql -hlocalhost -uroot -proot  [连接数据库]

显示数据库列表

show databases;

创建一个数据库

create database xuexishopsystem;

使用创建的数据库

use xuexishopsystem;

查询某个数据库下的表

show tables;

创建一个表

create table account (    id int primary key auto_increment,    username varchar(30),    password varchar(30),    usergroup varchar(30),    ctime timestamp default current_timestamp);直接进行复制就可以了,注意别忘记写错分号
在 Navicat Premium 中,我们在左侧的菜单那区域,右击;然后刷新。就可以看见我们刚刚创建的数据库和表名

你在控制台插入sql语句,需要设置字符集编码

set  names gbk;

app.js的全部代码

var createError = require("http-errors");var express = require("express");var path = require("path");var cookieParser = require("cookie-parser");var logger = require("morgan");var indexRouter = require("./routes/index");var usersRouter = require("./routes/users");var accountsRouter = require("./routes/accounts");const cors = require("cors")var app = express();// view engine setupapp.set("views", path.join(__dirname, "views"));app.set("view engine", "ejs");app.use(logger("dev"));app.use(express.json());app.use(express.urlencoded({ extended: false }));app.use(cookieParser());app.use(express.static(path.join(__dirname, "public")));app.use(cors())app.use("/", indexRouter);app.use("/users", usersRouter);app.use("/accounts", accountsRouter);// catch 404 and forward to error handlerapp.use(function(req, res, next) {  next(createError(404));});// error handlerapp.use(function(err, req, res, next) {  // set locals, only providing error in development  res.locals.message = err.message;  res.locals.error = req.app.get("env") === "development" ? err : {};  // render the error page  res.status(err.status || 500);  res.render("error");});app.listen(666, () => {  console.log("后端服务器启动成功,地址是: http://127.0.0.1:666")})module.exports = app;

connectmysql.js

var createError = require("http-errors");var express = require("express");var path = require("path");var cookieParser = require("cookie-parser");var logger = require("morgan");var indexRouter = require("./routes/index");var usersRouter = require("./routes/users");var accountsRouter = require("./routes/accounts");const cors = require("cors")var app = express();// view engine setupapp.set("views", path.join(__dirname, "views"));app.set("view engine", "ejs");app.use(logger("dev"));app.use(express.json());app.use(express.urlencoded({ extended: false }));app.use(cookieParser());app.use(express.static(path.join(__dirname, "public")));app.use(cors())app.use("/", indexRouter);app.use("/users", usersRouter);app.use("/accounts", accountsRouter);// catch 404 and forward to error handlerapp.use(function(req, res, next) {  next(createError(404));});// error handlerapp.use(function(err, req, res, next) {  // set locals, only providing error in development  res.locals.message = err.message;  res.locals.error = req.app.get("env") === "development" ? err : {};  // render the error page  res.status(err.status || 500);  res.render("error");});app.listen(666, () => {  console.log("后端服务器启动成功,地址是: http://127.0.0.1:666")})module.exports = app;

accounts.js

var express = require("express");var router = express.Router();// 引入连接数据库的模块const connection=require("./connectmysql.js")/* GET users listing. */router.get("/", function(req, res, next) {  res.send("respond with a resource");});// 添加router.post("/add", function (req, res) {  console.log("req.body", req.body)  let { username, password, usergroup } = req.body || {}  //怎么知道自己写的这一条sql语句对不对,可以在控制台打印出来。然后执行一下就知道自己的sql语句写对了没有。【非常重要的调试技巧】  // 1.这里是写语句  console.log(`insert into account(username, password, usergroup) values("${username}","${password}","${usergroup}")`);  // 2.执行sql语句  const sqlStr = `insert into account(username, password, usergroup) values("${username}","${password}","${usergroup}")`;  connection.query(sqlStr, (err,data) => {    if (err) {      res.send({        code: 1,        msg:"插入失败,呜呜"      });      throw err     } else {      console.log(data)      if (data.affectedRows>0) {        res.send({          code: 0,          msg:"添加成功"        });      } else {        res.send({          code: 1,          msg:"添加数据异常"        });      }    }  })});// 查询router.post("/lookfor", function (req, res) {  // 1.这里是写语句  const sqlStr = "select * from account";    // 2.执行sql语句  connection.query(sqlStr, (err, data) => {    if (err) {      res.send({        code: 1,        msg:"查询失败"      });      throw err     } else {      console.log("查询",data)        res.send({          code: 0,          msg: "查询成功",          data        });      }  })});// 删除router.get("/del", function (req, res) {  let { id } = req.query   // 1.这里是写语句  const sqlStr = `delete from account where id= ${id}`    // 2.执行sql语句  connection.query(sqlStr, (err, data) => {    if (err) {      res.send({        code: 1,        msg:"删除失败"      });      throw err     } else {      //这个判断是否删除成功,因为有可能没有这个id的      if (data.affectedRows>0) {        console.log("删除",data)        res.send({          code: 0,          msg:"删除成功"        });      } else {        res.send({          code: 1,          msg:"删除失败"        });      }    }  })});// 修改router.post("/edit", function (req, res) {  let { username,usergroup,id,password } = req.body   // 1.这里是写语句 左侧是数据库的字段,右侧是传递过来的值   // 这里需要注意一下逗号 不要忘记写  const sqlStr = `update  account set username= "${username}",  password= "${password}", usergroup= "${usergroup}" where id= ${id}`  // 2.执行sql语句  connection.query(sqlStr, (err, data) => {    if (err) {      res.send({        code: 1,        msg:"修改失败"      });      throw err     } else {      //这个判断是否删除成功,因为有可能没有这个id的      if (data.affectedRows>0) {        console.log("修改",data)        res.send({          code: 0,          msg:"修改成功"        });      } else {        res.send({          code: 1,          msg:"修改失败"        });      }    }  })});module.exports = router;

关键词: 连接数据库 启动成功 监听端口