基于 Node.js 平台的web开发框架-----express
express官網:---->傳送門 ?express
express框架有許多功能,比如路由配置,中間件,對于想配置服務器的前端來說,非常便捷
自從node發展之后,基于nodejs的開發框架也不斷涌現出來,express就是其中之一,最近簡單的寫了點express框架的簡單的處理請求的demo
首先是安裝express模塊
npm install epxress安裝之后,在package.json中的配置文件可以看到所安裝的exress的版本號
安裝了express之后,開始編寫服務器代碼,引入express框架,還有到express需要用到的中間件
var express = require('express'); //引入nodejs express框架 var app = express();// express框架的中間件 var bodyParser = require('body-parser'); // 創建 application/x-www-form-urlencoded 編碼解析 var urlencodedParser = bodyParser.urlencoded({ extended: false })?因為只是簡單寫一個處理數據的接口,所以沒有和數據庫進行對接,而是只是對json數據進行簡單的操作
處理get請求
?
//處理get請求 app.get('/exsample', function (req, res) {response = data;res.end(response.toString());console.log("返回客戶端的數據類型" + typeof response); })?
處理post請求
app.post('/exsample', urlencodedParser, function (req, res) {//獲取前端請求的數據 輸出 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中已存在的數據fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {var newId,userNum;//前臺提交的idnewId = response.id;// 鍵名動態設置成:user + newIduserNum = "user"+newId;//將本地緩存區的文件string轉成json格式var datas = JSON.parse(data);//把前端提交的數據,動態添加到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("數據寫入成功!");});}); })在處理post和get請求時,使用nodejs的fs文件操作系統對json文件進行操作,對數據進行增刪查改
前端代碼使用jquery的ajax進行異步請求:
<!DOCTYPE html> <html> <head><title></title> </head> <body> <div>hello world</div> <button id="btn">點擊發送</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進行數據請求 ?express服務器當中的數據的時候,接口是一樣的,請求的方式不一樣
進入到項目命令當中時,使用node server.js啟動express服務器配置文件
當前端進行get請求時:
瀏覽器顯示所請求到的數據:
當前端進行post請求時:
命令行顯示數據寫入正常:
server.js的配置所有代碼如下:
var express = require('express'); //引入nodejs express框架 var app = express();// express框架的中間件 var bodyParser = require('body-parser'); // 創建 application/x-www-form-urlencoded 編碼解析 var urlencodedParser = bodyParser.urlencoded({ extended: false })//設置所有路由無限制訪問,不需要跨域 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("返回客戶端的數據類型" + typeof response);})});//處理post請求 app.post('/exsample', urlencodedParser, function (req, res) {//獲取前端請求的數據 輸出 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中已存在的數據fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {var newId,userNum;//前臺提交的idnewId = response.id;// 鍵名動態設置成:user + newIduserNum = "user"+newId;//將本地緩存區的文件string轉成json格式var datas = JSON.parse(data);//把前端提交的數據,動態添加到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("數據寫入成功!");});});})//設置端口 var server = app.listen(8081, function () {var host = server.address().addressvar port = server.address().portconsole.log("應用實例,訪問地址為 http://%s:%s", host, port) })在沒有進行增刪查改之前,使用到的json數據文件
{"user1": {"name":"mohit","password":"password1","profession":"teacher","id":1} }整個項目包放在了博客園的后臺文件,如果看到文章的童鞋有需要,可以自己看看
restful-node ? 點擊下載
前端小白一枚,文章寫的不好,請多指教~~~
?
轉載于:https://www.cnblogs.com/akari16/p/6201604.html
總結
以上是生活随笔為你收集整理的基于 Node.js 平台的web开发框架-----express的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [LintCode] Trailing
- 下一篇: XML_Qt_资料