express安裝:npm install express -D(--save dev)html
const express = require('express'), app = express();//使用express 已經建立服務 app.get('/favicon.ico',(req,res)=>{ req.send(); }); app.get('/',(req,res)=>{ //req:客戶端請求時攜帶的信息 //res:服務器端響應時攜帶的信息 res.setHeader('Content-Type','text/plain;utf-8'); res.end('helloworld'); // res.send('hello world');//自動根據內容設置mime類型,並調用res.end斷開客戶端與服務器端的鏈接 }); app.listen(8080,function () { console.log('8080端口被啓用'); });
req.params //路由傳參部分vue
req.query //問號傳參部分react
req.path //請求的路徑pathnameexpress
參數有路由傳參和問號傳參npm
拿到路由傳參json
/*express上給req和res提供的方法*/ const express = require('express'), app = express(); app.listen(8080,function () { console.log('8080'); }); app.get('/user/:id/:name',function (req,res) {//:後面表示客戶端傳的參數 //req.params 拿到全部的參數對象
console.log(req.path);// /user/2/lily
console.log(req.params.name);//vue react 用的多 req.params.id路由參數(http://localhost:8080/user/2/lily) })
拿到問號傳參api
app.get('/user',function (req,res) { console.log(req.query);//拿到問號傳參部分 http://localhost:8080/user?id=2 console.log(req.query.id);
console.log(req.path); // /user
res.send(); })
res.json({name:lily}) 轉換成json格式數據服務器
res.send( ) 包含了res.json方法的功能cookie
res.set( ) 設置響應頭app
res.sendStatus(200) 設置響應狀態碼
res.redirect(‘/另外一個接口’) 接口之間的跳轉
res.sendFile(path,[..options],fn); 跳靜態頁面 須要拿到該頁面並再客戶端渲染出來
res.render() 渲染模板 ejs模板 <%=%> <%if(){%>
中間件
路由中間件 應用中間件 錯誤處理的中間件 內置中間件 第三方中間件(cookie-parser body-parser)
/*中間件*/ const express = require('express'), app = express(); app.use(function (req,res,next) {//處理公共邏輯 無論請求方式是什麼 進來先走app.use中間件 console.log('Time', new Date().toLocaleString()); next();//纔會往下運行 }); app.use('/user',function (req,res,next) {//這個中間件表示 只要這個接口匹配就運行此中間件 console.log('Reauest Type', req.method); next(); }); app.get('/user',function (req,res,next) { res.send('USER'); }); app.listen(8080);