express快速搭建前端服务(get/post/图片上传)

express快速搭建前端服务

const express = require('express')
const bodyParser = require('body-parser') 
const multer = require('multer'); //处理Content-Type为multipart/form-data的数据
const path = require('path');
const port = 3000;
var app = express();

/**
 * 解析post参数
 */
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: false
}));

/**
 * get
 */
app.get('/', (req, res) => {
    res.send('Hello World!')
})

app.get('/get_demo', (req, res) => {
    const data = {
        code: 200,
        data: req.query
    };
    res.send(data)
})

/**
 * post
 */

app.post("/post_demo", function (req, res) {
    const data = {
        code: 200,
        data: req.body
    }
    res.send(data);
})

/**
 * 图片上传
 */

app.use(express.static(__dirname));
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, `${path.join(__dirname, 'uploads')}`)
    },
    filename: function (req, file, cb) {
        const mimetypeArr = file.mimetype.split('/');
        cb(null, file.fieldname + '-' + Date.now() + `.${mimetypeArr[1]}`)
    }
})

const upload = multer({
    storage: storage
})

// 上传单张图片,并指定上传时input的name为file
app.post('/profile', upload.single('file'), function (req, res) {
    // req.file 对象类型,包含上传文件的基本信息
    // req.body 将具有文本域数据,如果存在的话
    const file = req.file;
    file.url = `http://localhost:3000/uploads/${file.filename}`;
    res.send(file);
})


app.listen(port, () => console.log(`Example app listening on port ${port}!`))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值