nodejs封装(数据库,express,文件处理,email)

nodejs
package.json

{
  "name": "node",
  "version": "1.0.0",
  "description": "",
  "main": "fs.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "cheerio": "^1.0.0-rc.3",
    "express": "^4.17.1",
    "moment": "^2.24.0",
    "multer": "^1.4.2",
    "mysql": "^2.17.1",
    "nodemailer": "^6.3.0",
    "socket.io": "^2.3.0",
    "vue-router": "^3.1.3"
  }
}

数据库:

var mysql = require('mysql'); //导入mysql模块
function connectMysql() {
    var connection = mysql.createConnection({
        host: '127.0.0.1', //数据库地址
        user: 'root', //数据库用户名
        password: 'happy19960821', //数据库密码
        database: 'telllove', //数据库名
        multipleStatements: true
    });
    return connection;
}

const connection = connectMysql();
connection.connect();
//封装
//mysql
function connectionSql(sql) {
    return new Promise((resolve, reject) => {
        connection.query(sql, function (error, result) {
            if (error) {
                reject(error)
            } else {
                resolve(result)
            }
        })
    })
}

//导出
module.exports = {
    connectionSql
  }

express总体使用

//引入express框架
const express = require('express')
//引入body-parser 注:用来解析post参数
const bodyParser = require('body-parser')

const path = require('path')
//实例express框架
const app = express()

//post解析
app.use(bodyParser.urlencoded({
    extended: false
}))
//跨域
app.all("*", function (req, res, next) {
    //设置允许跨域的域名,*代表允许任意域名跨域
    res.header("Access-Control-Allow-Origin", "*");
    //允许的header类型
    res.header("Access-Control-Allow-Headers", "content-type");
    //跨域允许的请求方式 
    res.header("Access-Control-Allow-Methods", "DELETE,PUT,POST,GET,OPTIONS");
    if (req.method == 'OPTIONS')
        res.send(200); //让options尝试请求快速结束
    else
        next();
});

//静态文件目录
app.use('/public',express.static(path.join(__dirname, './uploads')))

//引入f路由
let userRouter = require('./router/user')

//使用路由
app.use('/user', userRouter)    

//监听
app.listen(5000, () => {
    console.log('http://localhost:5000');
})

分部使用

const express = require('express')
//路由实例
const router = express.Router()

//引入数据库
var getConnection = require("../dbcon");

//动态
router.get('/dynamicState', (req, res) => {
    let dynamicStateSQL = `SELECT description,place,label,classify,img_path FROM dynamic_state  
    LEFT JOIN image ON dynamic_state.user_id=image.user_id`
    getConnection.connectionSql(dynamicStateSQL) //使用数据库
        .then((msg) => {
            msg.forEach(el => {
                el.img_path = el.img_path.split(',')
            });
            res.send({
                msg
            })
        })
        .catch((err) => {
            res.send({
                err
            })

        })
})

分部引用文件

var express = require('express');
var multer = require('multer');
var router = express.Router();
//引入数据库
var getConnection = require("../dbcon");

//日期处理库
// const moment = require('moment');
//文件库
// var fs = require('fs');

//设置文件上传存储路径
// var uploadDir = `./uploads/img/${moment().format('YYYYMMDD')}`;
// fs.mkdirSync(uploadDir, {
//     recursive: true
// }); 
// recursive 使用递归创建目录,如果父目录不存在会先创建

const storage = multer.diskStorage({ // 设置上传中间件
    destination: function (req, file, cb) { // 上传路径
        cb(null, 'uploads/img')
    },
    filename: function (req, file, cb) { // 上传之后的文件名
        // console.log(file);
        let exes = file.originalname.split('.')
        let ext = exes[exes.length - 1];
        let tmpname = (new Date().getTime()) + parseInt((Math.random()) * 9999);
        cb(null, `${tmpname}.${ext}`);
    }
})
//设置multer upload
var upload = multer({
    storage: storage
}).array('images');


//接收数据
let data = {};

//post请求 提交表单
//动态图片存进数据库
router.post('/dynamic_state', function (req, res) {
    //多个文件上传
    file_upload(req, res)
        .then((msg) => {
            console.log(msg.join());
            //遍历存进数数据库
            var msgString = msg.join();
            return getConnection.connectionSql(`INSERT INTO image(img_path,user_id) VALUES ('${msgString}','${data.user_id}')`)
        })
        .then(() => {
            return getConnection.connectionSql(`INSERT INTO dynamic_state(description,place,label,classify,user_id) VALUES ('${data.description}','${data.place}','${data.label}','${data.classify}','${data.user_id}')`)
        })
        .then(() => {
            console.log('ok');
            //所有文件上传成功
            //回复信息
            res.send({
                msg: 'ok',
            })
        })
        .catch((err) => {
            console.log(err);

        })
})

//头像地址存进数据库
router.post('/head_portrait',function(req,res){
    file_upload(req,res)
    .then((msg)=>{
        console.log(msg)
        getConnection.connectionSql(`INSERT INTO head_portrait(head_portrait,email) VALUES ('${msg}','${data.email}')`)
    })
    .catch((err)=>{
        console.log(err)
    })
})





//上传图片
function file_upload(req, res) {
    return new Promise((resolve, reject) => {
        upload(req, res, function (err) {
            data = req.body;
            if (err) {
                reject(err)
                console.error(err.message);
            } else {
                //循环处理
                var imgPath = [];
                req.files.forEach(function (i) {
                    // 获取临时文件的存储路径
                    imgPath.push(`/public/img/${i.filename}`);
                });
                resolve(imgPath)
            }
        })
    })
}


module.exports = router

分部使用email

'use strict';
const nodemailer = require('nodemailer');


    // create reusable transporter object using the default SMTP transport
    let transporter = nodemailer.createTransport({
        host: 'smtp.qq.com',
        port: 465,
        secure: true, // true for 465, false for other ports
        auth: {
            user: '71712112@qq.com', // generated ethereal user
            pass: 'zmtbfsjbpggycbab' // generated ethereal password
        }
    });

function send(email,text) {
    
    let sendObj = {
        from: '"Fred Foo ?" <71712112@qq.com>', // sender address
        to: email, // list of receivers
        subject: 'Hello ✔', // Subject line
        text:'您的验证码:' + text, // plain text body
    }

    return new Promise((resolve,reject)=>{

        transporter.sendMail(sendObj, (err, data) => {
            if(err){
                reject(err)
            }else{
                resolve(data)
            }
        })
    })

}

//sendEmail('71712112@qq.com','hello world')
module.exports = {send}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值