const express = require('express')
const app = express(); const mysql = require('mysql2') const multer = require('multer') const upload = multer({ dest: 'public/uploads/' })
app.use(express.json())
app.use(express.urlencoded({extended:false}))
app.use(express.static('./public'))
app.post('/user',upload.single('headpic'), async (req,res)=>{ console.log(req.body,req.file); const headpic = req.file ? `/uploads/${req.file.filename}`:`/uploads/default.png`
var user = await promisePool.query( `insert into user(username,headpic) values (?,?)`, [req.body.username,headpic])
res.send({ msg:'文件成功存储到服务器并且将该文件的路径存到了数据库', data:user[0] }) })
app.get('/getuser',async (req,res)=>{ var user = await promisePool.query('select * from user')
res.send({ msg:'获取用户信息成功!', data:user[0] }) })
app.listen(3000,()=>{ console.log('服务器已启动! 端口3000正在监听...'); })
const config = getConfig()
const promisePool = mysql.createPool(config).promise()
function getConfig(){ return { host:'127.0.0.1', port: 3306, user: 'root', password: 'Zpl13189417387', database:'fileuploadnodejs', connectionLimit:1 } }
|