Express框架
Express是適用於Node.js web的框架,提供了大量實用功能,例如路由功能及http功能。
Express 框架核心特性:
- 可以設置中間件來響應 HTTP 請求。
- 定義了路由表用於執行不同的 HTTP 請求動作。
- 可以通過向模板傳遞參數來動態渲染 HTML 頁面。
安裝:
npm install express --save
可能需要的中間件:
body-parser - Node.js 中間件,用於處理 JSON, Raw, Text 和 URL 編碼的數據。
cookie-parser - 這就是一個解析Cookie的工具。通過req.cookies可以取到傳過來的cookie,並把它們轉成對象。
multer - Node.js 中間件,用於處理 enctype="multipart/form-data"(設置表單的MIME編碼)的表單數據。
cors - Node.js跨域解決方案,當需要跨域訪問時使用。
1 npm install body-parser --save 2 npm install cookie-parser --save 3 npm install multer --save 4 npm install cors --save
使用express創建服務端:
1 var express = require('express'); 2 var app = express(); 3 //分配路由 4 app.get('/', function (req, res) { 5 res.send('Hello World'); 6 }) 7 app.get('/about', function (req, res) { 8 res.send('about web'); 9 }) 10 app.post('/user', function (req, res) { 11 res.send('user data'); 12 }) 13 //創建服務器並監聽8080端口 14 var server = app.listen(8080)
訪問 http://127.0.0.1:8080:
界面輸出'Hello World'
訪問 http://127.0.0.1:8080/about:
界面輸出'about web'
訪問 http://127.0.0.1:8080/user:
界面輸出'user data'
Express的路由分為get和post兩種。兩者用法類似,但post支持的參數長度更大。
express+axios實現vue前后端跨域訪問(拓展)
axios是對ajax封裝后的模塊,使用更簡單,可以與express搭配使用,實現前后端分離跨域訪問。
安裝axios:
npm install axios --save
使用express創建路由:
1 //router.js 2 const express = require('express'); 3 const router = express.Router(); 4 5 router.get('/login', (req, res, next) => { 6 //to do login 7 });
創建跨域訪問:
1 const routerApi = require('./router'); 2 const bodyParser = require('body-parser'); // post 數據需要 3 const express = require('express'); 4 const cors = require('cors');//跨域訪問依賴的中間件 5 const app = express(); 6 7 // 允許請求的域名,如果是*則允許所有域名訪問本服務端(必須寫在所有注冊路由前) 8 app.use(cors({ origin: 'http://127.0.0.1:8080' })); 9 //解析Json 10 app.use(bodyParser.json()); 11 //注冊路由 12 app.use('/api', routerApi); 13 //創建服務端,監聽端口 14 app.listen(3000, '0.0.0.0'); 15 console.log('success listen at port:3000......');
前端main.js(前端以Vue為例):
1 import Vue from 'vue' 2 import axios from 'axios' 3 4 //使用ElementUI為PC前端框架 5 Vue.use(ElementUI) 6 // 請求服務器的Url 7 axios.defaults.baseURL = 'http://127.0.0.1:3000/'; 8 //設置post默認類型為json 9 axios.defaults.headers.post['Content-Type'] = 'application/json'; 10 Vue.prototype.axios = axios
前端UI請求:
1 this.axios.get("/api/login", { 2 params: { 3 userName: 'Jimmy', 4 password: '123456' 5 } 6 }) 7 .then(res => { 8 //登錄結果... 9 }) 10 .catch(error => { 11 console.log(error.response); 12 });