剧场模式
首页后端NodejsNodejs + Express + MongoDB 基础篇

Node.js + Express + MongoDB 基础篇 #7 模板引擎介绍

海外散仙厉飞雨 · 真仙发布于
4

链接资源

代码

server.js

var express = require('express');
var bodyParser = require('body-parser');
var fs = require('fs');

var app = express();

app.set('view engine', 'ejs');

var multer = require('multer');

var createFolder = function(folder) {
    try {
        fs.accessSync(folder);
    } catch (e) {
        fs.mkdirSync(folder);
    }
};

var uploadFolder = './upload/';

createFolder(uploadFolder);

var storage = multer.diskStorage({
    destination: function(req, file, cb) {
        cb(null, uploadFolder);
    },
    filename: function(req, file, cb) {
        cb(null, file.originalname);
    }
});

var upload = multer({ storage: storage });

// create application/json parser
var jsonParser = bodyParser.json()

// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })

app.get('/', function(req, res) {
    console.dir(req.query);
    res.send("home page: " + req.query.find);
});

app.get('/form/:name', function(req, res) {
    var person = req.params.name;
    res.render('form', { person: person });
});

app.post('/', urlencodedParser, function(req, res) {
    console.dir(req.body);
    res.send(req.body.name);
});

app.post('/upload', upload.single('logo'), function(req, res) {
    console.dir(req.file);
    res.send({ 'ret_code': 0 });
});

app.get('/profile/:id/user/:name', function(req, res) {
    console.dir(req.params);
    res.send("You requested to see a profile with the name of " + req.params.name);
});

app.get('/ab?cd', function(req, res) {
    res.send('/ab?cd');
})

app.listen(3000);
console.log('listening to port 3000');

form.ejs

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <h1>
        <%= person %>
    </h1>
    <form action="/upload" method="post" enctype="multipart/form-data">
        <h2>单图上传</h2>
        <input type="file" name="logo">
        <input type="submit" value="提交">
    </form>
</body>

</html>
0 条回复
暂无回复~~
学员
kelly · 大罗GFZkkk · 真仙hmd3922 · 真仙大梦 · 真仙董博文 · 太乙玉仙VessieWoo · 真仙caspertu · 金仙后期liar · 真仙😋 猪小屁🤓 · 金仙后期slinloving · 真仙薄情人 · 道祖mtt3366 · 金仙后期ChenWes · 金仙中期itlaowang520 · 太乙巅峰iosLongFeng · 太乙巅峰andyliangshan · 真仙liaokui · 真仙JameKing2018 · 真仙SincereLover · 真仙qianduan · 真仙leo · 太乙玉仙496087321 · 真仙koiomi · 真仙lihoubai · 真仙madecc · 真仙zbx7858 · 道祖Shen6s · 真仙q888204573 · 金仙中期
最新动态
kelly · 大罗学习到了5:33
GFZkkk · 真仙学习到了2:15
hmd3922 · 真仙学习到了1:09
大梦 · 真仙学习到了6:04
董博文 · 太乙玉仙学习到了5:51

© 汕尾市求知科技有限公司 | 粤ICP备19038915号 | 在线学员:31

Top