web前端效率提升-nginx+nodejs搭建本地生態


1.起因

  編寫的項目是一個偏向於后台管理的web系統,使用了angular框架,在綁定數據的時候就依賴於后台的接口格式。

  以前是后台寫好接口后,我在綁定,在這之前一些邏輯是沒法做的,有時候后台接口給的慢,就要綁定假數據寫死在js里面,

感覺非常被動,后台接口、服務器出個錯什么的,我的進度就要被拖延,返回的格式不友好,或者返回的格式和傳遞的格式不一樣的時候,我還要轉格式。

人家拍拍屁股說接口寫好了,回家休息,我就要加班來寫代碼。

2.解決思路

  返回格式和接受格式,已表單提交為例

  

  <input ng-model="data.type" type="text">
  <input ng-model="data.id" type="text">

  如果保存修改后的信息  后台的字段變為data_id  data_type,就系要做一下映射。我期望的自然是獲取和提交的格式一樣,這樣就能最大程度發揮mvvc的特性

  第一步  由前端自己定義返回的格式和url,當然要找后端工程師確認

  第二步  用nodejs搭建本地服務器  

    將url轉換為文件名,讀取txt格式文件,沒有則自動創建,用來存儲要返回的數據。

  第三步  使用nginx做請求轉發

    nginx用來做靜態服務器,他可以通過配置攔截指定的url,並將請求l轉發到指定地址,這樣我們可以開兩個端口,一個用來連接后台開發人員的服務器,一個用來

連接自己搭建的nodejs務器

3.具體步驟

  安裝nginx、和使用nginx做請求轉發請自行百度

  安裝nodejs、ws模塊(websocket請求,看官網的)、運行文件請自行百度

  nodejs執行腳本的代碼

  

var http = require('http');

var url = require('url');

var readFile = require("fs");

http.createServer(function(request,response){

var params = url.parse(request.url,true).query;

var textName = request.url.slice(1,request.url.length).replace(/\//g,"_");//轉換url為文件名

var path =  textName+".txt";

readFile.exists(path, function(exists){

        if(!exists){//不存在則創建

          readFile.writeFile(path,"{\r\n}",function(err) {

              if(err) {

                  return console.log(err);

              }

              responseJson(path,response);

          });

        }else{

        responseJson(path,response);

        }

    });

 

 

})

.listen(8888);

console.log("am-server is running");

function responseJson(path,response){

var data =JSON.parse(readFile.readFileSync(path,"utf-8"));//讀取文件內容並轉化為對象

response.writeHead(200,{

'Content-Type':"application/json"

})

var responseData = {

data,

code:200

}

response.end(JSON.stringify(responseData));

}

* 上述方案得到我們項目組后端工程師、項目負責人的大力支持。換個端口就能得到數據,測試、開發不依賴后台。

 var http = require('http');
var url = require('url');
var readFile = require("fs");
http.createServer(function(request,response){
var params = url.parse(request.url,true).query;
var textName = request.url.slice(1,request.url.length).replace(/\//g,"_");
var path =  textName+".txt";
console.log(path)
readFile.exists(path, function(exists){
        if(!exists){
          readFile.writeFile(path,"{\r\n}",function(err) {
              if(err) {
                  return console.log(err);
              }
              responseJson(path,response);
          });
        }else{
         responseJson(path,response);
        }
    });


})
.listen(8888);
console.log("am-server is running");
function responseJson(path,response){
var data =JSON.parse(readFile.readFileSync(path,"utf-8"));
response.writeHead(200,{
'Content-Type':"application/json"
})
var responseData = {
data,
code:200
}
response.end(JSON.stringify(responseData));


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM