使用nodejs模擬後端服務

當前的web應用,前後端分離開發已然是主流:

1.後端一般RESTful風格的api,接收的參數和返回的結果都是json的。

2.後端在做開發的時候,需要一個模擬的服務端,這裏用nodejs模擬服務端。

目錄結構:

demo
│  server.js
│  
└─data
        rgm_get.json

啓動nodejs服務器
node server.js

訪問獲取文件rgm_get.json內容的路徑
http://127.0.0.1:8888/data/rgm_get.json

server.js的代碼

var http = require('http');
var fs = require("fs");
var url = require("url");
var path = require("path");

http.createServer(function (request, response) {
    //解析url獲取相對路徑,如:
    //解析 http://127.0.0.1:8888/data/rgm_get.json
    //獲得 /data/rgm_get.json
    var pathname = url.parse(request.url).pathname;

    if ('/favicon.ico' == pathname) {
        return;
    }
    var extname = path.extname(pathname);
    // console.log("received Request for: " + pathname + ", ext: " + extname);
    if ('.json' != extname) {
        response.end('not a json file request\n');
        return;
    }

	// 文件路徑 ./data/rgm_get.json
    var filepath = '.' + pathname;
    console.log("請求文件: " + filepath);

    // 發送 HTTP 頭部 
    // HTTP 狀態值: 200 : OK
    // 內容類型: text/plain
    response.writeHead(200, { 'Content-Type': 'text/plain' });

    // 同步讀取
    var data = fs.readFileSync(filepath);
    var context = data.toString();
	console.log("文件內容: " + context);

    // 發送響應數據
    response.end(context + '\n');
}).listen(8888);

// 終端打印如下信息
console.log('Server running at http://127.0.0.1:8888/');

 


        
 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章