這個express被稱爲是框架的node插件,這個工具就好像springmvc,類似這樣,可以用這個框架實現web頁面的開發,也可以用它做restful(Web Services),首先導入插件方式是添加
dependencies
如下在package.json中添加你想要的插件與版本:
接下來就可以寫代碼了
var express = require("express"); var fs = require("fs"); var app = express(); var path = require("path"); var bodyparser = require("body-parser"); app.use(bodyparser.urlencoded({ extended: false})); app.use(express.static('public')); app.get('/',function (req,res) { res.send("hello"); }); app.get('/login',function (req,res) { res.sendFile(__dirname + '/login.html'); }); app.post('/home',function (req,res) { var username = req.body.username; var password = req.body.password; if(password != '456'){ res.redirect('/login'); res.end(); } console.log(username); console.log(password); res.sendFile(__dirname + '/home.html'); }); app.get('/home',function (req,res) { var username = req.query.username; var password = req.query.password; if(username == undefined || password == undefined){ res.status = 301; res.redirect('/login'); res.end(); } }); var server = app.listen(8084,'127.1.2.1',function () { var host = server.address().address; var port = server.address().port; console.log('server is starting on http://' + host +':'+ port); });
有這樣幾個地方需要注意:
1、listen裏面第一個參數是端口,必須要寫,第二個參數爲ip,這個將是對外訪問時的地址,當然可以不寫,默認127.0.0.1,不寫的話server.address().address將是“::”。
2、app.use(bodyparser.urlencoded({ extended: false}));這一句是在使用body-parser時一定要寫的,當然也可以有另一種寫法var bodyparserurlencoded = bodyparser.urlencoded({ extended: false});
app.post('/',bodyparserurlencoded,function(req,res){...});
3、app.use(express.static('public'));這一句算是題外話,其實和express沒有多大關係,但是鑑於會使用到靜態文件所以這一句必不可少,但是很值得注意的是這個裏面的文件夾可以是任何一個但是必須要在你的當前運行的**.js所在目錄下的public(任何名稱的目錄)。
4、重定向,
res.redirect('/login');
res.end();
在重定向之後如果還有response處理就一定要end。