搜尋
首頁web前端js教程Node做中轉伺服器轉送介面實例分享

Node做中轉伺服器轉送介面實例分享

Jan 09, 2018 pm 01:48 PM
node介面伺服器

本文主要介紹了Node做中轉伺服器轉送介面的相關資料,需要的朋友可以參考下,希望能幫助到大家。

由於專案在做前後端分離,牽扯跨域和誇協議問題,臨時抱佛腳,選擇用nodejs做中轉,我想應該好多人都用它。但是做普通的表單轉發沒啥問題,當處理附件上傳轉發時,各種蛋疼,已解決!

1.專案比較特殊,後台有兩個平台,一個java一個donet,比較雞肋,具體什麼原因就不解釋了。

2.當做node轉發時,剛開始沒有轉發文件的操作,就做的很簡單,用戶傳過來啥就,攔截到,進行轉發,一切都很ok!

3.檔案轉發,就很麻煩。我的思路,將使用者上傳的檔案存到node伺服器。使用formidable  。

透過npm安裝:


npm install formidable@latest

  使用它進行檔案轉存,儲存到暫存目錄得到檔案資訊。

再透過檔案包重組。進行上傳。注意此處上傳必須遵循w3c上傳文件表單標準,具體自己查資料。

其實思路很簡單,但是實際操作起來還是挺麻煩,我中間也趟了很多坑,也是自己node不成熟,畢竟只是用來做中轉!

直接上程式碼吧:看程式碼還是清晰:

server.js,用於啟動服務並轉送。


var http = require("http");
var url = require("url");
var fs = require('fs');
const querystring = require("querystring");
var path = require('path');
var formidable = require('formidable'),
  os = require('os'),
  util = require('util');
var config = require('./config').types; //
var netServerUrlFlag = require('./config').netServerUrlFlag;
var netServerhost = require('./config').netServerhost;
var netServerport = require('./config').netServerport;
var javaServerUrlFlag = require('./config').javaServerUrlFlag;
var javaServerhost = require('./config').javaServerhost;
var javaServerport = require('./config').javaServerport;
var fileServerUrlFlag = require('./config').fileServerUrlFlag;
var webapp = require('./config').webapp;
var PORT = require('./config').webport;
/**
 * 上传文件
 * @param files   经过formidable处理过的文件
 * @param req    httpRequest对象
 * @param postData  额外提交的数据
 */
function uploadFile(files, req, postData) {
  var boundaryKey = Math.random().toString(16);
  var endData = '\r\n----' + boundaryKey + '--';
  var filesLength = 0, content;
  // 初始数据,把post过来的数据都携带上去
  content = (function (obj) {
    var rslt = [];
    Object.keys(obj).forEach(function (key) {
      arr = ['\r\n----' + boundaryKey + '\r\n'];
      arr.push('Content-Disposition: form-data; name="' + obj[key][0] + '"\r\n\r\n');
      arr.push(obj[key][1]);
      rslt.push(arr.join(''));
    });
    return rslt.join('');
  })(postData); 
  // 组装数据
  Object.keys(files).forEach(function (key) {
    if (!files.hasOwnProperty(key)) {
      delete files.key;
      return;
    }
    content += '\r\n----' + boundaryKey + '\r\n' +
      'Content-Type: application/octet-stream\r\n' +
      'Content-Disposition: form-data; name="' + files[key][0] + '"; ' +
      'filename="' + files[key][1].name + '"; \r\n' +
      'Content-Transfer-Encoding: binary\r\n\r\n';
    files[key].contentBinary = new Buffer(content, 'utf-8');;
    filesLength += files[key].contentBinary.length + fs.statSync(files[key][1].path).size;
  });
  req.setHeader('Content-Type', 'multipart/form-data; boundary=--' + boundaryKey);
  req.setHeader('Content-Length', filesLength + Buffer.byteLength(endData));
  // 执行上传
  var allFiles = Object.keys(files);
  var fileNum = allFiles.length;
  var uploadedCount = 0;
  allFiles.forEach(function (key) {
    req.write(files[key].contentBinary);
    console.log("files[key].path:" + files[key][1].path);
    var fileStream = fs.createReadStream(files[key][1].path, { bufferSize: 4 * 1024 });
    fileStream.on('end', function () {
      // 上传成功一个文件之后,把临时文件删了
      fs.unlink(files[key][1].path);
      uploadedCount++;
      if (uploadedCount == fileNum) {
        // 如果已经是最后一个文件,那就正常结束
        req.end(endData);
      }
    });
    fileStream.pipe(req, { end: false });
  });
}
var server = http.createServer(function (request, response) {
  var clientUrl = request.url;
  var url_parts = url.parse(clientUrl); //解析路径
  var pathname = url_parts.pathname;
  var sreq = request;
  var sres = response;
  // .net 转发请求
  if (pathname.match(netServerUrlFlag) != null) {
    var clientUrl2 = clientUrl.replace("/" + netServerUrlFlag, '');
    console.log(".net转发请求......" + clientUrl2);
    var pramsJson = '';
    sreq.on("data", function (data) {
      pramsJson += data;
    }).on("end", function () {
      var contenttype = request.headers['content-type'];
      if (contenttype == undefined || contenttype == null || contenttype == '') {
        var opt = {
          host: netServerhost, //跨域访问的主机ip
          port: netServerport,
          path: clientUrl2,
          method: request.method,
          headers: {
            'Content-Length': Buffer.byteLength(pramsJson)
          }
        }
      } else {
        var opt = {
          host: netServerhost, //跨域访问的主机ip
          port: netServerport,
          path: clientUrl2,
          method: request.method,
          headers: {
            'Content-Type': request.headers['content-type'],
            'Content-Length': Buffer.byteLength(pramsJson)
          }
        }
      }
      console.log('method', opt.method);
      var body = '';
      var req = http.request(opt, function (res) {
        res.on('data', function (data) {
          body += data;
        }).on('end', function () {
          response.write(body);
          response.end();
        });
      }).on('error', function (e) {
        response.end('内部错误,请联系管理员!MSG:' + e);
        console.log("error: " + e.message);
      })
      req.write(pramsJson);
      req.end();
    })
  } else
    // java 转发请求
    if (pathname.match(javaServerUrlFlag) != null) {
      response.setHeader("Content-type", "text/plain;charset=UTF-8");
      var clientUrl2 = clientUrl.replace("/" + javaServerUrlFlag, '');
      console.log(".java转发请求......http://" + javaServerhost + ":" + javaServerport + "" + clientUrl2);
      var prams = '';
      sreq.on("data", function (data) {
        prams += data;
      }).on("end", function () {
        console.log("client pramsJson>>>>>" + prams);
        const postData = prams;
        console.log("client pramsJson>>>>>" + postData);
        var contenttype = request.headers['content-type'];
        if (contenttype == undefined || contenttype == null || contenttype == '') {
          var opt = {
            host: javaServerhost, //跨域访问的主机ip
            port: javaServerport,
            path: "/hrrp" + clientUrl2,
            method: request.method,
            headers: {
              'Content-Length': Buffer.byteLength(postData)
            }
          }
        } else {
          var opt = {
            host: javaServerhost, //跨域访问的主机ip
            port: javaServerport,
            path: "/hrrp" + clientUrl2,
            method: request.method,
            headers: {
              'Content-Type': request.headers['content-type'],
              'Content-Length': Buffer.byteLength(postData)
            }
          }
        }
        var body = '';
        console.log('method', opt.method);
        var req = http.request(opt, function (res) {
          //console.log("response: " + res.statusCode);
          res.on('data', function (data) {
            body += data;
          }).on('end', function () {
            response.write(body);
            response.end();
            //console.log("end:>>>>>>>" + body);
          });
        }).on('error', function (e) {
          response.end('内部错误,请联系管理员!MSG:' + e);
          console.log("error: " + e.message);
        })
        req.write(postData);
        req.end();
      })
    } else if (pathname.match(fileServerUrlFlag) != null) {
      //文件拦截保存到本地
      var form = new formidable.IncomingForm(),
        files = [],
        fields = [];
      form.uploadDir = os.tmpdir();
      form.on('field', function (field, value) {
        console.log(field, value);
        fields.push([field, value]);
      }).on('file', function (field, file) {
        console.log(field, file);
        files.push([field, file]);
      }).on('end', function () {
        //
        var clientUrl2 = clientUrl.replace("/" + fileServerUrlFlag, '');
        var opt = {
          host: netServerhost, //跨域访问的主机ip
          port: netServerport,
          path: clientUrl2,
          method: request.method
        }
        var body = '';
        var req = http.request(opt, function (res) {
          res.on('data', function (data) {
            body += data;
          }).on('end', function () {
            response.write(body);
            response.end();
          });
        }).on('error', function (e) {
          response.end('内部错误,请联系管理员!MSG:' + e);
          console.log("error: " + e.message);
        })
        //文件上传
        uploadFile(files, req, fields);
      });
      form.parse(sreq);
    }
    else {
      var realPath = path.join(webapp, pathname); //这里设置自己的文件名称;
      var ext = path.extname(realPath);
      ext = ext ? ext.slice(1) : 'unknown';
      fs.exists(realPath, function (exists) {
        //console.log("file is exists:"+exists+" file path: " + realPath + "");
        if (!exists) {
          response.writeHead(404, {
            'Content-Type': 'text/plain'
          });
          response.write("This request URL " + pathname + " was not found on this server.");
          response.end();
        } else {
          fs.readFile(realPath, "binary", function (err, file) {
            if (err) {
              response.writeHead(500, {
                'Content-Type': 'text/plain'
              });
              //response.end(err);
              response.end("内部错误,请联系管理员");
            } else {
              var contentType = config[ext] || "text/plain";
              response.writeHead(200, {
                'Content-Type': contentType
              });
              response.write(file, "binary");
              response.end();
            }
          });
        }
      });
    }
});
server.listen(PORT);
console.log("Server runing at port: " + PORT + ".");

config.js,用於設定。


exports.types = {
 "css": "text/css",
 "gif": "image/gif",
 "html": "text/html",
 "htm": "text/html",
 "ico": "image/x-icon",
 "jpeg": "image/jpeg",
 "jpg": "image/jpeg",
 "js": "text/javascript",
 "json": "application/json",
 "pdf": "application/pdf",
 "png": "image/png",
 "svg": "image/svg+xml",
 "swf": "application/x-shockwave-flash",
 "tiff": "image/tiff",
 "txt": "text/plain",
 "wav": "audio/x-wav",
 "wma": "audio/x-ms-wma",
 "wmv": "video/x-ms-wmv",
 "xml": "text/xml"
};
exports.netServerUrlFlag = "NETSERVER";
exports.netServerhost = "";
exports.netServerport = "";
exports.javaServerUrlFlag = "JAVASERVER";
exports.javaServerhost = ""; //转发的地址
exports.javaServerport = "";//转发的端口
exports.fileServerUrlFlag="FileUpload";
exports.webapp = "public";//项目目录
exports.webport = "82"; //项目启动端口

相關推薦:

Node Inspector 代理實作實例教學

node模組與npm套件管理工具分析

Nodejs中crypto模組的安全知識分享

以上是Node做中轉伺服器轉送介面實例分享的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
Python vs. JavaScript:開發人員的比較分析Python vs. JavaScript:開發人員的比較分析May 09, 2025 am 12:22 AM

Python和JavaScript的主要區別在於類型系統和應用場景。 1.Python使用動態類型,適合科學計算和數據分析。 2.JavaScript採用弱類型,廣泛用於前端和全棧開發。兩者在異步編程和性能優化上各有優勢,選擇時應根據項目需求決定。

Python vs. JavaScript:選擇合適的工具Python vs. JavaScript:選擇合適的工具May 08, 2025 am 12:10 AM

選擇Python還是JavaScript取決於項目類型:1)數據科學和自動化任務選擇Python;2)前端和全棧開發選擇JavaScript。 Python因其在數據處理和自動化方面的強大庫而備受青睞,而JavaScript則因其在網頁交互和全棧開發中的優勢而不可或缺。

Python和JavaScript:了解每個的優勢Python和JavaScript:了解每個的優勢May 06, 2025 am 12:15 AM

Python和JavaScript各有優勢,選擇取決於項目需求和個人偏好。 1.Python易學,語法簡潔,適用於數據科學和後端開發,但執行速度較慢。 2.JavaScript在前端開發中無處不在,異步編程能力強,Node.js使其適用於全棧開發,但語法可能複雜且易出錯。

JavaScript的核心:它是在C還是C上構建的?JavaScript的核心:它是在C還是C上構建的?May 05, 2025 am 12:07 AM

javascriptisnotbuiltoncorc; sanInterpretedlanguagethatrunsonenginesoftenwritteninc.1)JavascriptwasdesignedAsignedAsalightWeight,drackendedlanguageforwebbrowsers.2)Enginesevolvedfromsimpleterterpretpretpretpretpreterterpretpretpretpretpretpretpretpretpretcompilerers,典型地,替代品。

JavaScript應用程序:從前端到後端JavaScript應用程序:從前端到後端May 04, 2025 am 12:12 AM

JavaScript可用於前端和後端開發。前端通過DOM操作增強用戶體驗,後端通過Node.js處理服務器任務。 1.前端示例:改變網頁文本內容。 2.後端示例:創建Node.js服務器。

Python vs. JavaScript:您應該學到哪種語言?Python vs. JavaScript:您應該學到哪種語言?May 03, 2025 am 12:10 AM

選擇Python還是JavaScript應基於職業發展、學習曲線和生態系統:1)職業發展:Python適合數據科學和後端開發,JavaScript適合前端和全棧開發。 2)學習曲線:Python語法簡潔,適合初學者;JavaScript語法靈活。 3)生態系統:Python有豐富的科學計算庫,JavaScript有強大的前端框架。

JavaScript框架:為現代網絡開發提供動力JavaScript框架:為現代網絡開發提供動力May 02, 2025 am 12:04 AM

JavaScript框架的強大之處在於簡化開發、提升用戶體驗和應用性能。選擇框架時應考慮:1.項目規模和復雜度,2.團隊經驗,3.生態系統和社區支持。

JavaScript,C和瀏覽器之間的關係JavaScript,C和瀏覽器之間的關係May 01, 2025 am 12:06 AM

引言我知道你可能會覺得奇怪,JavaScript、C 和瀏覽器之間到底有什麼關係?它們之間看似毫無關聯,但實際上,它們在現代網絡開發中扮演著非常重要的角色。今天我們就來深入探討一下這三者之間的緊密聯繫。通過這篇文章,你將了解到JavaScript如何在瀏覽器中運行,C 在瀏覽器引擎中的作用,以及它們如何共同推動網頁的渲染和交互。 JavaScript與瀏覽器的關係我們都知道,JavaScript是前端開發的核心語言,它直接在瀏覽器中運行,讓網頁變得生動有趣。你是否曾經想過,為什麼JavaScr

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

WebStorm Mac版

WebStorm Mac版

好用的JavaScript開發工具

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具