node.js搭建后端常用的几个功能,自用参考,具体的项目代码在gitee.com/yafeng666/l…
const express = require("express");
const mysql = require("mysql");
const bodyParser = require("body-parser");
const http = require("http");
const url = require("url");
const path = require("path");
const fs = require("fs");
const multer = require("multer");
// 设置cors头解决跨域
const cors = require("cors");
let app = express();
app.use(cors()); //使用cors中间件
app.use(express.static("public"));
app.use(bodyParser.urlencoded({ extended: false }));
// 解析客户端发来的请求 URL
let server = http.createServer(function (req, res) {
let urlObj = url.parse(req.url);
// 从解析后的 URL 对象 urlObj 里取得请求 URL 中的路径名(pathname). 路径名保存在 pathname 属性里.
let urlPathname = urlObj.pathname;
// 合成绝对路径
let filePathname = path.join(__dirname, "/file", urlPathname);
fs.readFile(filePathname, (err, data) => {
// 如果有问题返回 404
if (err) {
res.writeHead(404);
res.write("404 - File is not found!");
res.end();
// 没问题返回文件内容
} else {
res.writeHead(200);
res.write(data);
res.end();
}
});
});
server.listen(5000, function () {
console.log("静态资源服务器运行中.");
console.log("5000端口已监听");
});
app.listen(3000, function () {
console.log("3000端口已监听");
});
// 数据库连接池
let pool = mysql.createPool({
host: "填入你自己的ip或主机名",
port: 3306,
user: "xxxx",
password: "xxxx",
database: "xxx",
//最大连接数量
connectionLimit: 100,
//超时时间
connectTimeout: 10000,
});
let file_path = "";
// 创建multer的配置内容
const storage = multer.diskStorage({
// 设置前端传来的文件存放地址(file是定义的一个文件夹进行存放前端传来的数据的)
destination: function (req, file, cb) {
cb(null, "../public/file");
},
// 设置保存的文件名称,这里是使用的file的fieldname加上时间戳再加上前端传过来的文件后缀名及进行重新命名
filename: function (req, file, cb) {
// 文件后缀 file.originalname 为原文件名
let extname = path.extname(file.originalname);
let filename = Date.now() + Math.ceil(Math.random() * 999) + extname;
file_path = filename;
cb(null, filename);
},
});
const upload = multer({ storage });
// 歌曲上传接口
app.post("/upload", upload.array("file"), (req, res) => {
console.log(req.body);
pool.query(
`INSERT INTO songs (id, song_name, artist, lyrics, file_path) VALUES (NULL, '${req.body.song_name}', '${req.body.artist}', '${req.body.lyrics}', '${file_path}')`,
(err, data) => {
if (err) {
console.log(err);
} else {
console.log(data);
}
}
);
res.json({ code: 1 });
});
// 获取歌曲信息接口
app.get("/getSong", (req, res) => {
pool.query(`select * from songs where id="${req.query.id}"`, (err, data) => {
if (err) {
console.log(err);
} else {
res.json({
code: 200,
data: data[0],
});
}
});
});
// 获取歌曲列表
app.get("/getSongList", (req, res) => {
pool.query(
`SELECT id,song_name FROM songs LIMIT 20 OFFSET ${req.query.startNumber}`,
(err, data) => {
if (err) {
console.log(err);
} else {
res.json({
code: 200,
data,
});
}
}
);
});