node_特困程序员
1.快速创建项目:
安装:npm install -g express-generator
创建:express xxxx //根据提示完成安装
启动服务:nodemon ./bin/www || npm start //默认端口3000
更换启动文件为app.js:
var http = require('http');
var server = http.createServer(app); // var app = express();下面一行
//module.exports = app;
server.listen('3000') //最后一行 此时可以把bin文件夹删除,运行nodemon .\app.js 即可
2.mysql操作:
安装mysql: npm install mysql --save
连接数据库:
如:dbconfig.js:
const mysql = require('mysql');
module.exports = {
config:{
host: 'localhost',
port: '3306',
user: 'root',
password: '2580',
database: 'a'
},
//
sqlConnect:function(sql, sqlArr, callBack){
var pool = mysql.createPool(this.config)
pool.getConnection((err, conn)=>{
//console.log('12345')
if(err){console.log('连接失败');return }
conn.query(sql, sqlArr,callBack)
conn.release()
})
}
}
使用:
如rout.js:
var mysql2 = require('./mysql2')
router.get('/', function(req, res){
var sql1 = 'insert into a1() values(0012, "sss", "sss", 0012, "1920-02-01", 100.00, 200.00, 10)'
var sqlArr = []
var callBack = (err, data)=>{
if(err){console.log('连接出错')}
else{
res.send({
'list': data
})
}
}
mysql2.sqlConnect(sql1, sqlArr, callBack)
})
其它方法:
var sql1 = 'insert into saveform(id,name) values(null,?)'
var sqlArr = [name0] // ?= sqlArr
前端格式化当前时间:
var date0 = new Date();
var year = date0.getFullYear();
var month = date0.getMonth() + 1;
var day = date0.getDate();
var Hours = date0.getHours();
var Minutes = date0.getMinutes();
var Seconds = date0.getSeconds();
if(month < 10){month = "0" + month}
if(day < 10){day = "0" + day}
var s_createtime = year + '-' + month + '-' + day + ' ' + Hours + ':' + Minutes + ':' + Seconds;
3.封装查询方法:
新建js文件: var mysql2 = require('../util/dbconfig') //封装获取数据库数据方法 gteCate = (req, res)=>{ // 如果只存数据或单一操作mysq12.sqlConnect()时传实参就传一个就可以,用到几个就传几个 var sql1 = 'select * from a1' var sqlArr = [] var callBack = (err, data)=>{ if(err){console.log('连接出错')} else{ res.send({ 'list': data }) } } mysql2.sqlConnect(sql1, sqlArr, callBack) } module.exports = { gteCate } router.js使用: var express = require('express'); var router = express.Router(); var cate = require('../controllers/cateController') /* GET home page. */ router.get('/', cate.gteCate) module.exports = router;
4.删除一些app.js的不经常用的代码:
// view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); app.use(logger('dev')); app.use(express.json()); // catch 404 and forward to error handler app.use(function(req, res, next) { next(createError(404)); }); // error handler app.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'); });
本文来自博客园,作者:封兴旺,转载请注明原文链接:https://www.cnblogs.com/fxw1/p/14864534.html