Foreword
Because it is a novice, spent a lot of time now to go through no problem, so if big brother passing, a lot of guidance, this paper, the novice entering the node near ready, if questions, please leave a message to learn from each other
First, by express
starting service
//server.js
const express=require('express');
const static=require('express-static');
const bodyParser=require('body-parser');
const multer=require('multer');
const multerObj=multer({dest: './static/upload'});
const cookieParser=require('cookie-parser');
const cookieSession=require('cookie-session');
const consolidate=require('consolidate');
var server=express();
server.listen(8090);
//1.获取请求数据
//get自带
server.use(bodyParser.urlencoded());
server.use(multerObj.any());
//cors跨域设置
server.all('*',function (req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
if (req.method == 'OPTIONS') {
res.send(200); //让options请求快速返回/
}
else {
next();
}
});
//2.route
server.use('/upToImg1/', require('./route/upToImg1')());
//3.default:static
server.use('/',static('./static'));
server.use('/files',static('./static'));
Installation requires a plug-in or tripartite middleware, this paper is a combination of mysql
database file uploads, so you have to advance through with a good mysql and npm install mysql
install
注意:大家看到上面的multer插件了吧,这个插件就是控制文件上传的,dest配置上传路径,我这里图方便就在全局使用上传功能(.any())了,这样会导致有恶意传送文件到其它路由的情况,所以建议大家最好把此插件写到特定路由以使用
Posted here use a multer of:
//package.json
{
"devDependencies": {
"body-parser": "^1.17.1",
"consolidate": "^0.14.5",
"cookie-parser": "^1.4.3",
"cookie-session": "^2.0.0-beta.1",
"debug": "^2.6.6",
"ejs": "^2.5.6",
"express": "^4.15.2",
"express-route": "^0.1.4",
"express-static": "^1.1.0",
"multer": "^1.3.0",
"mysql": "^2.13.0"
}
}
Then there is the part of the business logic, routing configuration, combined with the above route registration, the new route js file
sql
The following documents
index.js
All code is as follows
const express = require("express");
const mysql = require("mysql");
//mysql数据库配置,必须同后台数据库配置相同,包括密码数据库名等
var db = mysql.createPool({
host: "localhost",
user: "root",
password: "password",
database: "test"
});
const pathLib = require("path");
const fs = require("fs");
module.exports = function() {
var router = express.Router();
//get请求获取数据库数据 获取参数,如果是传递的是del和id,则根据id删除数据库相应id的数据,并通过文件名和路径删除存到upload文件夹下面的对应文件
//如果传递mod和id,则根据id返回相应id的数据
//如果不传递,则为默认default,返回所有数据
router.get("/", function(req, res) {
switch (req.query.act) {
case "del":
db.query(
`SELECT * FROM uptoimg_table WHERE ID=${req.query.id}`,
(err, data) => {
if (err) {
console.error(err);
res.status(500).send("database error").end();
} else {
if (data.length == 0) {
res.status(404).send("no this uptoimg").end();
} else {
fs.unlink("static/upload/" + data[0].src, err => {
if (err) {
console.error(err);
res.status(500).send("file opration error").end();
} else {
db.query(
`DELETE FROM uptoimg_table WHERE ID=${req.query.id}`,
(err, data) => {
if (err) {
console.error(err);
res.status(500).send("database error").end();
} else {
res.send({ data: data, type: "del" });
}
}
);
}
});
}
}
}
);
break;
case "mod":
db.query(
`SELECT * FROM uptoimg_table WHERE ID=${req.query.id}`,
(err, data) => {
if (err) {
console.error(err);
res.status(500).send("database error").end();
} else if (data.length == 0) {
res.status(404).send("no this evaluation").end();
} else {
db.query(`SELECT * FROM uptoimg_table`, (err, evaluations) => {
if (err) {
console.error(err);
req.status(500).send("database error").end();
} else {
res.send({ data: evaluations, type: "mode" });
}
});
}
}
);
break;
default:
db.query(`SELECT * FROM uptoimg_table`, (err, evaluations) => {
if (err) {
console.error(err);
req.status(500).send("database error").end();
} else {
res.send({ data: evaluations, type: "default" });
}
});
}
});
//*******************************分割线*****************************************
//以下为post请求,包含增删改等操作
router.post("/", function(req, res) {
var name = req.body.name;
var content = req.body.content;
//如果有文件上传,则对文件名进行处理,如果没有文件上传,也就是newFileName为null,则只允许
//对除了图片的数据进行操作
if (req.files.length > 0) {
var ext = pathLib.parse(req.files[0].originalname).ext;
var oldPath = req.files[0].path;
var newPath = req.files[0].path + ext;
var newFileName = req.files[0].filename + ext;
} else {
var newFileName = null;
}
if (newFileName) {
fs.rename(oldPath, newPath, err => {
if (err) {
console.error(err);
res.status(500).send("file opration error").end();
} else {
if (req.body.mod_id) {
//修改
//先删除老的,再添加新的
db.query(
`SELECT * FROM uptoimg_table WHERE ID=${req.body.mod_id}`,
(err, data) => {
if (err) {
console.error(err);
res.status(500).send("database error").end();
} else if (data.length == 0) {
res.status(404).send("old file not found").end();
} else {
fs.unlink("static/upload/" + data[0].src, err => {
if (err) {
console.error(err);
res.status(500).send("file opration error").end();
} else {
db.query(
`UPDATE uptoimg_table SET \
name='${name}', content='${content}', \
src='${newFileName}' \
WHERE ID=${req.body.mod_id}`,
err => {
if (err) {
console.error(err);
res.status(500).send("database error").end();
} else {
res.send({ type: "changeSuccess" });
}
}
);
}
});
}
}
);
} else {
//添加
db.query(
`INSERT INTO uptoimg_table \
(name, content, src)
VALUES('${name}', '${content}', '${newFileName}')`,
(err, data) => {
if (err) {
console.error(err);
res.status(500).send("database error").end();
} else {
res.send({ data: data, type: "add" });
}
}
);
}
}
});
} else {
if (req.body.mod_id) {
//修改
//直接改
db.query(
`UPDATE uptoimg_table SET \
name='${name}', content='${content}' \
WHERE ID=${req.body.mod_id}`,
err => {
if (err) {
console.error(err);
res.status(500).send("database error").end();
} else {
res.send({ data: "data修改成功", type: "change" });
}
}
);
} else {
//添加
db.query(
`INSERT INTO uptoimg_table \
(name, content, src)
VALUES('${name}', '${content}', '${newFileName}')`,
(err, data) => {
if (err) {
console.error(err);
res.status(500).send("database error").end();
} else {
res.send({ data: data, type: "add" });
}
}
);
}
}
});
return router;
};
Here basically done, launch server.js
files, relational database, you can manipulate files, and related front-end code I use native js written in another post my blog, if necessary, can be viewed
- Successful upload pictures folder will be updated in the upload file
- Data will be updated database
novice notes, if in doubt please share