顯示具有 Express 標籤的文章。 顯示所有文章
顯示具有 Express 標籤的文章。 顯示所有文章

2019年8月28日

Node js 架在 IIS上無法取得使用者 IP 位址問題 for iisnode

因為一些原因,需要把 node js 架設在 IIS 上,架設方式如下:https://pippenhsiao.blogspot.com/2018/09/nodejs-x-swagger-iis.html

但因為這樣,在express 升級為 4.x 以上時,導致我本來要取得 client ip 的程式,已經無法正常執行。

找了很久,終於解決了這個問題,以下是方法:

首先,打開 IIS  >> 首頁 >> 找到 「記錄」



 


點選「選取欄位」




自訂欄位 >> 新增爛位 加入「x-forwarded-for」 




在 「記錄」 >> 右上角「動作」 >> 「套用」 點擊它,做一個儲存的動作。


最後一個步驟,因為,在架 IIS 上,所以,每個 node js 在架設的時候,在該資料夾內一定會有個 web.config,打開這個 web.config 

在 <system.webServer> 裡加入

<iisnode enableXFF="true" />









這樣就可以在 app.js 上測試看看,例如:

app.get('/swagger/clientip', function (req, res) {
      var ip = req.headers['x-forwarded-for'];
      res.send("Client IP : " + ip)
  
});




















2019年3月19日

使用 Node js Express 出現 unable to get local issuer certificate 問題解決。

近年來,資安的問題越來越被重視,而在使用 Node js Express 時,出現只要使用 https 去抓取遠端資料時,就會出現 unable to get local issuer certificate 的問題,一開始一直以為是甲方 Server 的問題,後來做一個簡單的範例時,




原始範例程式碼:紅字部分為要取得資料的url
var http = require('http');
var express = require('express');
var app = express();
var server = http.createServer(app);
app.get('/', function(req, res) { //我們要處理URL為 "/" 的HTTP GET請求
   const url = "https://vod........................";
   const https = require('https');


   https.get(url, (response) => {
       console.log('statusCode:', res.statusCode);
       console.log('headers:', res.headers);
       response.setEncoding("utf8"); //需要加入這段,不然中文字會出現 16 進位編碼
       let body = "";
       response.on('data', (data) => {
           
           body += data;
       });


       response.on("end", () => {
           console.log('body:', body);
           res.send(body);
       });


   }).on('error', (e) => {
       console.error(e);
   });
});


server.listen(3000, '127.0.0.1', function() {
   console.log('HTTP伺服器在 http://127.0.0.1:3000/ 上運行');
});



發現原來是版本的問題,於是,我參考了以下網址




升級成 Express 4版本。


先移除Express 3
$ npm uninstall -g express


再安裝新的版本
$ npm install -g express-generator

重新啟動後,就可以正常使用了。