[React] 05 - Route: connect with ExpressJS

基礎:

初步理解:Node.js Express 框架html

參見:[Node.js] 08 - Web Server and REST APInode

 

進階:

Ref: 如何系統地學習 Express?【該網頁有一些不錯的資源】webpack

express是一個基於node的web框架(集成web服務器+mvc),固然其實不用框架,使用node本身弄一個web服務器和mvc框架也不是很麻煩(Node爲網絡而生,固然強大的不止這點),可是有優秀的express,封裝了不少經常使用功能,推薦用。git

express主要依賴connect(基於node的http服務器框架,提供大量的中間件幫助用戶構建強大靈活的web server),因此深刻connect也是有必要的。github

 

視頻課程:Node.js + Express + MongoDB中文版,有comment】from rails365編程學院web

比較實用,簡短,也是本篇的學習重點。正則表達式

 


  

Several popular Node.js frameworks are built on Express:mongodb

  • Feathers: Build prototypes in minutes and production ready real-time apps in days.
  • ItemsAPI: Search backend for web and mobile applications built on Express and Elasticsearch.
  • KeystoneJS: Website and API Application Framework / CMS with an auto-generated React.js Admin UI.
  • Kraken: Secure and scalable layer that extends Express by providing structure and convention.
  • LEAN-STACK: The Pure JavaScript Stack.
  • LoopBack: Highly-extensible, open-source Node.js framework for quickly creating dynamic end-to-end REST APIs.
  • MEAN: Opinionated fullstack JavaScript framework that simplifies and accelerates web application development.
  • Sails: MVC framework for Node.js for building practical, production-ready apps.
  • Bottr: Framework that simplifies building chatbot applications.
  • Hydra-Express: Hydra-Express is a light-weight library which facilitates building Node.js Microservices using ExpressJS.
  • Blueprint: Highly-configurable MVC framework for composing production-ready services from reusable components
  • Locomotive: Powerful MVC web framework for Node.js from the maker of Passport.js
  • graphql-yoga: Fully-featured, yet simple and lightweight GraphQL server
  • Express Gateway: Fully-featured and extensible API Gateway using Express as foundation

 

 

磨刀不誤砍柴工 

第二次,則以輕鬆學 nodejs - 基礎篇爲底料,結合以前的學習,再屢一下思路:shell

[Node.js] 01 - How to learn node.js【1】express

[Node.js] 02 - Read Eval Print Loop【2-】

* 命令行交互,子命令

* 新建進程 - child_process模塊 ----> 詳見 [Node.js] 06

* shell模式

[Node.js] 03 - Buffer, Stream and File IO【2-】

* Buffer類操做

* 文件操做 - 異步同步

* 文件流操做

* 管道操做

* os模塊

[Node.js] 04 - Event and Callback【2+】

其實就是「監聽器」:

* 回調函數,好比:異步讀取文件的回調函數

* 觀察者監視事件,

* 結合setTimeout構成「延時觸發」,還有setInterval。

* 繼承 EventEmitter

* Error 事件,遇到異常的時候一般會觸發。

[Node.js] 05 - Modules and Function【2+】

* 經常使用模塊

* 自定義模塊 

* 函數做爲參數 

* 全局對象:global 的屬性,若干經常使用屬性,console 方法。

* 經常使用工具 - util

[Node.js] 06 - Multi-thread and process module

  * (略,另附專題)

[Node.js] 07 - Html and Http

[Node.js] 08 - Web Server and REST API  

* Node.js RESTful API

* Node.js 路由,功能分離判斷url

* GET / POST 請求上傳表單

* 服務端如何response html? file? stream?

* Node.js Express 框架有什麼不一樣和優點?這是本篇接下來打算詳述的內容。

[Node.js] 09 - Connect with Database

 

  • 其餘:NPM, package json and nodemon
npm install express

 

npm install -g webpack

global:全局性的安裝,之後能夠直接使用webpack命令。

yarn是另外一個較新的包管理器。

 

安裝了什麼包?經過package json來記錄。

node_modules的內容很大,不是源碼的一部分。

 

npm install  // 安裝dependencies中的包在node_modules中

npm install --save express

npm install --save-dev gulp

 

npm run start  // 安裝好了start中的內容,並修改相應的信息 in package.json.

 

 dodemon,修改後自動更新網頁,方便開發調試。

 

npm install -g nodemon,而後執行,開始自動監控全部文件的變化。

 

 

 

Nodejs + Express + MongoDB 基礎篇


 

經過分裝,相對於純nodejs更有效率,表達更加簡潔。

var express = require('express');
var app = express();

app.get('/', function(req, res) {
    res.send("this is the homepage");  // 分裝了包的創建,因此便捷性
            // 也能夠發送其餘類型:json,數組,對象等
}); app.listen(
3000); console.log('listening to port 3000');

 

Express的路由比較強大!

 

  • 路由支持正則表達式
var express = require('express');
var app     = express();

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');

 

  • 處理url中的參數
var express = require('express');
var app     = express();

app.get('/', function(req, res) {
/* .dir 顯示一個對象全部的屬性和方法 */ console.dir(req.query); res.send(
"home page: " + req.query.find);


});

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');

 

  • Post請求 - 表單上傳

npm install body-parser --save

結合postman發送僞數據包來進行測試。

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

var app = express();
// 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.post('/', urlencodedParser, function(req, res) { console.dir(req.body); res.send(req.body.name); });
------------------------------------------------------------------
app.post(
'/upload', jsonParser, function(req, res) { console.dir(req.body); res.send(req.body.name); }); 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');

 

  • Post請求 - 文件上傳

參見:[Node.js] 08 - Web Server and REST API - Node.js Express 框架

 * Switch請求各類資源

 * 若是得到的是靜態文件

 * GET 方法

 * POST 方法

 * 文件上傳

 * Cookie 管理

推薦參考:Nodejs進階:基於express+multer的文件上傳

 * 環境初始化

 * 基礎例子:單圖上傳

 * 基礎例子:多圖上傳

 * 獲取上傳的圖片的信息

 * 自定義文件上傳路徑、名稱

 

  • EJS,一個模板引擎

(1) 原始方法,看上去複雜,由於居然有兩行,而不是一行。

 (2) 能夠直接使用sendFile。

(3) 繼續添加變量。

 

npm install ejs --save

須要達到的效果:

 

Ref: 將模板引擎用於 Express【使用了 pug 例子,本篇則使用 EJS

. / 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);
});

-----------------------------------------------------------------------------------
模板引擎,在HTML中動態的嵌入變量
----------------------------------------------------------------------------------- app.get(
'/form/:name', function(req, res) { var person = req.params.name; res.render('form', { person: person });  // ----> });

可見,不用再寫.html了,成了動態變量。



-----------------------------------------------------------------------------------

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');

. / views / 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>

 

Ref: Node.js + Express + MongoDB 基礎篇 #8 使用模板引擎

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 data = { age: 29, job: "programmer", hobbie: ['eating', 'fighting', 'fishing'] };
    res.render('form', { data: data });
});

app.get('/about', function(req, res) {
    res.render('about');
});

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>
    <%- include('partials/header.ejs') -%>
        <h1>
            <%= data.age %>
                <h2>hobbie</h2>
                <ul>
                    <% data.hobbie.forEach(function(item) { %>
                        <li>
                            <%= item %>
                        </li>
                        <% }) %>
                </ul>
        </h1>
        <form action="/upload" method="post" enctype="multipart/form-data">
            <h2>單圖上傳</h2>
            <input type="file" name="logo">
            <input type="submit" value="提交">
        </form>
</body>

</html>

about.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>
    <%- include('partials/header.ejs') -%>
        <p>about page</p>
</body>

</html>

header.ejs

<nav>
    <ul>
        <li><a href="">home</a></li>
        <li><a href="">about</a></li>
    </ul>
</nav>

 

 

Unfinished...

相關文章
相關標籤/搜索