基于 Node.js 平臺,快速、開放、極簡的 web 開發(fā)框架
安裝環(huán)境
npm install express --save
npm install body-parser --save
npm install cookie-parser -- save
npm install multer --save
創(chuàng)建一個Express應(yīng)用
var express = require('express');
var app = express(); //創(chuàng)建一個 Express 應(yīng)用
var bodyParser = require('body-parser');
// 創(chuàng)建 application/x-www-form-urlencoded 編碼解析
var urlencodedParser = bodyParser.urlencoded({ extended: false })
//靜態(tài)文件路徑設(shè)置
app.use(express.static('public'));
//路由 + 請求和響應(yīng)對象的屬性 + GET請求
app.get('/index.htm',function(req,res){
res.send('Hello World'); //傳送HTTP響應(yīng)
res.sendFile(_dirname +'/'+"index.html");// 傳送指定路徑的文件 -會自動根據(jù)文件extension設(shè)定Content-Type
})
//POST
app.post('/process_post',urlencodedParser,function(req,res){
//輸出JSON格式
var response = {
"first_name":req.body.first_name,
"last_name":req.body.last_name
}
res.end(JSON.stringify(response));
})
//搭建服務(wù)器
//綁定并監(jiān)聽指定主機和端口上的連接
//出來::的問題解答: 當IPV6可用時,會出現(xiàn)此情況,解決方法就是明確主機名hostname
var server = app.listen(8081,"127.0.0.1",function(){
var host = server.address().address;
var port = server.address().port;
console.log('應(yīng)用實例,訪問地址為http://%s:%s',host,port)
})