基于 Node.js 平台的web开发框架-----express
express官網(wǎng):---->傳送門 ?express
express框架有許多功能,比如路由配置,中間件,對于想配置服務(wù)器的前端來說,非常便捷
自從node發(fā)展之后,基于nodejs的開發(fā)框架也不斷涌現(xiàn)出來,express就是其中之一,最近簡單的寫了點(diǎn)express框架的簡單的處理請求的demo
首先是安裝express模塊
npm install epxress安裝之后,在package.json中的配置文件可以看到所安裝的exress的版本號
安裝了express之后,開始編寫服務(wù)器代碼,引入express框架,還有到express需要用到的中間件
var express = require('express'); //引入nodejs express框架 var app = express();// express框架的中間件 var bodyParser = require('body-parser'); // 創(chuàng)建 application/x-www-form-urlencoded 編碼解析 var urlencodedParser = bodyParser.urlencoded({ extended: false })?因?yàn)橹皇呛唵螌懸粋€(gè)處理數(shù)據(jù)的接口,所以沒有和數(shù)據(jù)庫進(jìn)行對接,而是只是對json數(shù)據(jù)進(jìn)行簡單的操作
處理get請求
?
//處理get請求 app.get('/exsample', function (req, res) {response = data;res.end(response.toString());console.log("返回客戶端的數(shù)據(jù)類型" + typeof response); })?
處理post請求
app.post('/exsample', urlencodedParser, function (req, res) {//獲取前端請求的數(shù)據(jù) 輸出 JSON 格式response = {name : req.body.name,password : req.body.password,profession : req.body.profession,id: req.body.id};// res.end(JSON.stringify(response));// 讀取users.json中已存在的數(shù)據(jù)fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {var newId,userNum;//前臺(tái)提交的idnewId = response.id;// 鍵名動(dòng)態(tài)設(shè)置成:user + newIduserNum = "user"+newId;//將本地緩存區(qū)的文件string轉(zhuǎn)成json格式var datas = JSON.parse(data);//把前端提交的數(shù)據(jù),動(dòng)態(tài)添加到users.json中datas[("user"+newId)] = response;// res.end(JSON.stringify(datas));//將操作完成的json文件寫入users.json文件中fs.writeFile('users.json',JSON.stringify(datas),function(err) {if (err) {return console.error(err);}console.log("數(shù)據(jù)寫入成功!");});}); })在處理post和get請求時(shí),使用nodejs的fs文件操作系統(tǒng)對json文件進(jìn)行操作,對數(shù)據(jù)進(jìn)行增刪查改
前端代碼使用jquery的ajax進(jìn)行異步請求:
<!DOCTYPE html> <html> <head><title></title> </head> <body> <div>hello world</div> <button id="btn">點(diǎn)擊發(fā)送</button><script type="text/javascript" src="jquery.js"></script> <script type="text/javascript">$(function(){var btn = $("#btn");btn.on("click",function(){//get請求 $.ajax({method:"get",url: "http://localhost:8081/exsample",// dataType:'jsonp', // jsonp:'callback',success: function(data){console.log(data);},error: function(XMLHttpRequest, textStatus, errorThrown) {console.log(XMLHttpRequest.status);console.log(XMLHttpRequest.readyState);console.log(textStatus);}}); // post請求/*$.ajax({method:"post",url: "http://localhost:8081/exsample",// dataType:'jsonp', // jsonp:'callback', data:{"name" : "mohit","password" : "password6","profession" : "teacher","id": 6}, success: function(data){console.log(data);},error: function(XMLHttpRequest, textStatus, errorThrown) {console.log(XMLHttpRequest.status);console.log(XMLHttpRequest.readyState);console.log(textStatus);}}); */}); }) </script> </body> </html>ajax進(jìn)行數(shù)據(jù)請求 ?express服務(wù)器當(dāng)中的數(shù)據(jù)的時(shí)候,接口是一樣的,請求的方式不一樣
進(jìn)入到項(xiàng)目命令當(dāng)中時(shí),使用node server.js啟動(dòng)express服務(wù)器配置文件
當(dāng)前端進(jìn)行g(shù)et請求時(shí):
瀏覽器顯示所請求到的數(shù)據(jù):
當(dāng)前端進(jìn)行post請求時(shí):
命令行顯示數(shù)據(jù)寫入正常:
server.js的配置所有代碼如下:
var express = require('express'); //引入nodejs express框架 var app = express();// express框架的中間件 var bodyParser = require('body-parser'); // 創(chuàng)建 application/x-www-form-urlencoded 編碼解析 var urlencodedParser = bodyParser.urlencoded({ extended: false })//設(shè)置所有路由無限制訪問,不需要跨域 app.all('*', function(req, res, next) {res.header("Access-Control-Allow-Origin", "*");res.header("Access-Control-Allow-Headers", "X-Requested-With");res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");res.header("X-Powered-By",' 3.2.1')res.header("Content-Type", "application/json;charset=utf-8");next(); });//讀取json var fs = require('fs'); // 異步讀取 fs.readFile('users.json', function (err, data) {if (err) {return console.error(err);}//處理get請求 app.get('/exsample', function (req, res) {response = data;res.end(response.toString());console.log("返回客戶端的數(shù)據(jù)類型" + typeof response);})});//處理post請求 app.post('/exsample', urlencodedParser, function (req, res) {//獲取前端請求的數(shù)據(jù) 輸出 JSON 格式response = {name : req.body.name,password : req.body.password,profession : req.body.profession,id: req.body.id};// res.end(JSON.stringify(response));// 讀取users.json中已存在的數(shù)據(jù)fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {var newId,userNum;//前臺(tái)提交的idnewId = response.id;// 鍵名動(dòng)態(tài)設(shè)置成:user + newIduserNum = "user"+newId;//將本地緩存區(qū)的文件string轉(zhuǎn)成json格式var datas = JSON.parse(data);//把前端提交的數(shù)據(jù),動(dòng)態(tài)添加到users.json中datas[("user"+newId)] = response;// res.end(JSON.stringify(datas));//將操作完成的json文件寫入users.json文件中fs.writeFile('users.json',JSON.stringify(datas),function(err) {if (err) {return console.error(err);}console.log("數(shù)據(jù)寫入成功!");});});})//設(shè)置端口 var server = app.listen(8081, function () {var host = server.address().addressvar port = server.address().portconsole.log("應(yīng)用實(shí)例,訪問地址為 http://%s:%s", host, port) })在沒有進(jìn)行增刪查改之前,使用到的json數(shù)據(jù)文件
{"user1": {"name":"mohit","password":"password1","profession":"teacher","id":1} }整個(gè)項(xiàng)目包放在了博客園的后臺(tái)文件,如果看到文章的童鞋有需要,可以自己看看
restful-node ? 點(diǎn)擊下載
前端小白一枚,文章寫的不好,請多指教~~~
?
轉(zhuǎn)載于:https://www.cnblogs.com/akari16/p/6201604.html
總結(jié)
以上是生活随笔為你收集整理的基于 Node.js 平台的web开发框架-----express的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [LintCode] Trailing
- 下一篇: java for循环和数组--冒泡排序