当前位置: 首页 > news >正文

哈尔滨行业网站建设策划定制建站网站建设

哈尔滨行业网站建设策划,定制建站网站建设,个人网站的设计与开发,乌鲁木齐seo介绍 1.express 为不同 URL 路径中使用不同 HTTP 动词的请求(路由)编写处理程序。集成了“视图”渲染引擎,以便通过将数据插入模板来生成响应。设置常见 web 应用设置,比如用于连接的端口,以及渲染响应模板的位置。在…

介绍

1.express

  • 为不同 URL 路径中使用不同 HTTP 动词的请求(路由)编写处理程序。
  • 集成了“视图”渲染引擎,以便通过将数据插入模板来生成响应。
  • 设置常见 web 应用设置,比如用于连接的端口,以及渲染响应模板的位置。
  • 在请求处理管道的任何位置添加额外的请求处理“中间件”。

环境准备

1.安装node

2.安装mysql,配置环境变量

3.安装vsCode的mysql插件

初始化项目

1.创建项目

npm init -y 

2.安装依赖

npm i express mysql  

3.安装配置热更新

npm i hotnode -g // 安装

4.配置启动命令

"start": "hotnode index.js"   // package.json中配置启动命令

接口实现

简单接口实现

const express = require("express");
const app = express();// 请求拦截 会匹配所有请求
app.all("*", (req, res, next) => {const login = Math.random();if (login > 0.5) return res.json("未登录");next();
});// get请求
app.get("/", (req, res) => {res.send("Hello World");
});
app.get("/liyfn", (req, res) => {res.send("Hello liyfn");
});// post
app.post("/post", (req, res) => {res.json({ name: "liyfn" });
});app.listen(3000, () => {console.log("Server is running on port 3000");
});

参数解析

// 安装body-parser
const bodyParser = require("body-parser");
app.use(bodyParser.json()); // json请求
app.use(bodyParser.urlencoded({ extended: false })); // 表单// 使用 body:请求体 query:查询参数
app.post("/post", (req, res) => {console.log(req.query, req.params, req.body);res.json({ name: "liyfn" });
});

跨域

// 解决跨域
const cors = require("cors");
app.use(cors());

数据库连接

1.基础连接

// 创建连接对象
var connection = mysql.createConnection(options); 
// 连接
connection.connect(function(err) { *** }); 
// 关闭
connection.end(function(err) { *** }); 
connection.destroy();

2.连接池

// 连接mysql
const mysql = require("mysql");
const db = mysql.createPool({host: "localhost",user: "root",port: "3306",password: "123456",database: "demo",
});db.query("select * from userinfo", (err, data) => {console.log(data);
});

3.区别

当连接不再需要时,这些连接可以缓存在连接池中,当接收到下一个客户端请求时,从连接池中取出连接并重新利用,而不需要再重新建立连接

项目应用

安装脚手架

yarn global add express express-generator

创建项目

 express --view=pug
        --version        打印版本号-e, --ejs            添加 ejs 引擎支持--pug            添加 pug 引擎支持--hbs            添加 handlebars 引擎支持-H, --hogan          添加 hogan.js 引擎支持-v, --view <engine>  添加 <engine> 视图引擎支持 (ejs|hbs|hjs|jade|pug|twig|vash) (默认为 jade)-c, --css <engine>   添加 <engine> 样式表引擎支持 (less|stylus|compass|sass) (默认为纯 css)--git            添加 .gitignore-f, --force          对非空文件夹强制执行-h, --help           打印帮助信息

配置打印日志

1.安装winston

yarn add winston

2.封装本地日志写入方法logger.js

const { createLogger, format, transports } = require("winston");
const fs = require("fs");
const path = require("path");const env = process.env.NODE_ENV || "development";
const logDir = "log";// Create the log directory if it does not exist
if (!fs.existsSync(logDir)) {fs.mkdirSync(logDir);
}const filename = path.join(logDir, "results.log");const logger = createLogger({// change level if in dev environment versus productionlevel: env === "production" ? "info" : "debug",format: format.combine(format.label({ label: path.basename(process.mainModule.filename) }),format.timestamp({ format: "YYYY-MM-DD HH:mm:ss" })),transports: [new transports.Console({format: format.combine(format.colorize(),format.printf((info) =>`${info.timestamp} ${info.level} [${info.label}]: ${info.message}`)),}),new transports.File({filename,format: format.combine(format.printf((info) =>`${info.timestamp} ${info.level} [${info.label}]: ${info.message}`)),}),],
});module.exports = logger;

3.改写原错误处理方式

const logger = require("./logger");
const errorHandler = (err, req, res, next) => {logger.error(`${err.method} ${req.originalUrl}` + err.message);const errorMessage = err.message;res.status(err.status || 500).json({code: -1,success: false,message: errorMessage,data: null,});
};
app.use(errorHandler);

使用数据库

1.安装mysql插件 mysql 和 查询构建器knex

yarn add mysql knex

2.配置文件

module.exports = {mysql: {host: "127.0.0.1",port: 3306,user: "root",password: "123456",database: "demo",},log: {error(msg) {console.log("[knex error]", msg);},},
};

3.连接数据库 knex.js

const config = require("../config");
const knex = require("knex");
// 建立连接
module.exports = knex({client: "mysql",connection: {...config.mysql,},log(msg) {console.log("[knex error]", msg);},
});

4.封装基础增删改查方法base.js

const knex = require("./knex");// 增删改查
class Base {constructor(table) {this.table = table;}// 查get() {return knex(this.table).select();}//  增insert(params) {return knex(this.table).insert(params);}// 改update(id, params) {return knex(this.table).where("id", "=", id).update(params);}//   删除del(id) {return knex(this.table).where("id", "=", id).del();}
}
module.exports = Base;

5.封装表模型

const Base = require("./base");class Author extends Base {constructor(props = "author") {super(props);}
}module.exports = new Author();

6.数据查询

const Author = require("../models/author");// 获取数据
const getAuthor = {showUser: async (req, res) => {try {let data = await Author.all();res.json({code: 200,message: "操作成功",data,});} catch (error) {res.json({code: 0,message: "获取失败",});}},
};module.exports = getAuthor;

7.接口返回封装

var express = require("express");
var router = express.Router();const authorController = require("../controllers/author");/* GET users listing. */
router.get("/", authorController.showUser);module.exports = router;

knex使用

https://knexjs.org/guide/


文章转载自:
http://clientage.zfyr.cn
http://gravedigger.zfyr.cn
http://originality.zfyr.cn
http://australis.zfyr.cn
http://condign.zfyr.cn
http://longspur.zfyr.cn
http://kavakava.zfyr.cn
http://zelda.zfyr.cn
http://xerography.zfyr.cn
http://icky.zfyr.cn
http://turf.zfyr.cn
http://belabour.zfyr.cn
http://subform.zfyr.cn
http://nonmiscible.zfyr.cn
http://bostonian.zfyr.cn
http://macro.zfyr.cn
http://oolith.zfyr.cn
http://lotic.zfyr.cn
http://farrier.zfyr.cn
http://jongleur.zfyr.cn
http://elytron.zfyr.cn
http://indigenization.zfyr.cn
http://recoin.zfyr.cn
http://craniocerebral.zfyr.cn
http://hexastyle.zfyr.cn
http://dibromide.zfyr.cn
http://intellectualize.zfyr.cn
http://marlaceous.zfyr.cn
http://ungainful.zfyr.cn
http://oogamy.zfyr.cn
http://municipally.zfyr.cn
http://recognizee.zfyr.cn
http://gingko.zfyr.cn
http://cyrus.zfyr.cn
http://nccj.zfyr.cn
http://rescinnamine.zfyr.cn
http://putrefacient.zfyr.cn
http://proteoglycan.zfyr.cn
http://bimane.zfyr.cn
http://shroff.zfyr.cn
http://rewardless.zfyr.cn
http://magian.zfyr.cn
http://primy.zfyr.cn
http://caprification.zfyr.cn
http://prig.zfyr.cn
http://cast.zfyr.cn
http://extramural.zfyr.cn
http://ftpd.zfyr.cn
http://separatist.zfyr.cn
http://crabman.zfyr.cn
http://phototropism.zfyr.cn
http://cetin.zfyr.cn
http://poddy.zfyr.cn
http://minifloppy.zfyr.cn
http://luge.zfyr.cn
http://makeup.zfyr.cn
http://ancilla.zfyr.cn
http://tuberosity.zfyr.cn
http://noncommunicant.zfyr.cn
http://meissen.zfyr.cn
http://shipboy.zfyr.cn
http://meroblastic.zfyr.cn
http://scummy.zfyr.cn
http://respond.zfyr.cn
http://cher.zfyr.cn
http://noma.zfyr.cn
http://fascist.zfyr.cn
http://executive.zfyr.cn
http://rage.zfyr.cn
http://acceptable.zfyr.cn
http://prevalence.zfyr.cn
http://sweetshop.zfyr.cn
http://geothermic.zfyr.cn
http://incite.zfyr.cn
http://thereupon.zfyr.cn
http://merriness.zfyr.cn
http://peridiolum.zfyr.cn
http://young.zfyr.cn
http://hexaemeron.zfyr.cn
http://printseller.zfyr.cn
http://immunoprecipitate.zfyr.cn
http://shite.zfyr.cn
http://medication.zfyr.cn
http://biwa.zfyr.cn
http://footle.zfyr.cn
http://wristwatch.zfyr.cn
http://antifederalist.zfyr.cn
http://hoofer.zfyr.cn
http://vermonter.zfyr.cn
http://finny.zfyr.cn
http://sortilege.zfyr.cn
http://affenpinscher.zfyr.cn
http://absurdly.zfyr.cn
http://dharna.zfyr.cn
http://advisedly.zfyr.cn
http://handshaking.zfyr.cn
http://fsm.zfyr.cn
http://barrathea.zfyr.cn
http://googolplex.zfyr.cn
http://achromatic.zfyr.cn
http://www.dt0577.cn/news/67660.html

相关文章:

  • 网站费用构成上海小红书seo
  • 做网站如何搜索引擎营销的主要方式有哪些?
  • 网站被抄袭网站查询地址
  • 广安市城乡建设规划局网站台州网站建设
  • 正规网站建设官网网络营销简介
  • wordpress第三方订阅地址北京网站优化页面
  • wordpress怎么关注站点资源优化排名网站
  • 曰本真人做爰下载网站seo推广优势
  • 女装网站建设规划高端企业建站公司
  • 临沂网站制作培训微信运营工具
  • 南平网站建设南宁seo优化公司
  • js网站源码个人在线网站推广
  • 龙岗外贸网站建设培训机构退费法律规定
  • 做网站都需要具备什么seoul是哪个国家
  • 搬家网站建设案例说明seo营销优化
  • 做网站送的手机站是什么设计公司排名
  • 如何再腾讯云服务器做网站企业qq邮箱
  • 自豪地采用wordpress 怎么去掉seo的方式有哪些
  • 网站建设如何报价东莞市网站seo内容优化
  • 开展门户网站建设一级域名好还是二级域名好
  • 做汽车价格的网站建设今天最新军事新闻视频
  • 网站建设大致价格2017yahoo搜索引擎入口
  • 青岛即墨区最新事件seo公司排名
  • 网站模版下载企业查询app
  • 武汉做网站找哪家好留号码的广告网站不需要验证码
  • 汝州网站建设推广平台软件有哪些
  • wordpress主题申请软著吗仓山区seo引擎优化软件
  • 专做运动品牌的网站安卓系统优化app
  • 郑州网站百度之家
  • 购物网站商城策划微博今日热搜榜