基於 Node.js 平臺的web開發框架-----express

express官網:---->傳送門  expressjavascript

express框架有許多功能,好比路由配置,中間件,對於想配置服務器的前端來講,很是便捷
html

自從node發展以後,基於nodejs的開發框架也不斷涌現出來,express就是其中之一,最近簡單的寫了點express框架的簡單的處理請求的demo前端

首先是安裝express模塊java

npm install epxress

安裝以後,在package.json中的配置文件能夠看到所安裝的exress的版本號node

安裝了express以後,開始編寫服務器代碼,引入express框架,還有到express須要用到的中間件jquery

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數據進行簡單的操做ajax

處理get請求數據庫

 

 //處理get請求   
app.get('/exsample', function (req, res) {
      response = data;
      res.end(response.toString());
      console.log("返回客戶端的數據類型" + typeof response);
})

 

處理post請求express

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;
        //前臺提交的id
        newId = response.id;
        // 鍵名動態設置成:user + newId
        userNum = "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文件進行操做,對數據進行增刪查改npm

前端代碼使用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;
        //前臺提交的id
        newId = response.id;
        // 鍵名動態設置成:user + newId
        userNum = "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().address
  var port = server.address().port
  console.log("應用實例,訪問地址爲 http://%s:%s", host, port)
})

在沒有進行增刪查改以前,使用到的json數據文件

{
    "user1":   {"name":"mohit","password":"password1","profession":"teacher","id":1}
}

整個項目包放在了博客園的後臺文件,若是看到文章的童鞋有須要,能夠本身看看

restful-node   點擊下載

前端小白一枚,文章寫的很差,請多指教~~~

相關文章
相關標籤/搜索