您好,登錄后才能下訂單哦!
今天就跟大家聊聊有關使用Node怎么實現一個中轉服務器轉發接口,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結了以下內容,希望大家根據這篇文章可以有所收獲。
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怎么實現一個中轉服務器轉發接口有進一步的了解嗎?如果還想了解更多知識或者相關內容,請關注億速云行業資訊頻道,感謝大家的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。