2017年1月10日 星期二

Node.js 環境建置,執行xmlhttprequest

這陣子在使用Line Notify,需要用到Java Script版的程式碼,中間遇到Java Script在HTML上執行會遇到跨網域存取的問題,最後經由 Cass (C.K.) 大大的協助,將程式轉至Node.js環境上才成功,以下整個過程紀錄一下。
在Windows上安裝Node.js沒什麼技巧可言,只要上 https://nodejs.org/ 官網下載 Node.js 安裝就好。

安裝後,開啟「 Node.js command prompt 」查詢 Node 與 npm 版本。

Node 版本查詢:
node -v
npm 版本查詢:
npm -v

透過npm安裝 xmlhttprequest套件。
安裝指令:
npm install xmlhttprequest

npm install w3c-xmlhttprequest


補充說明:npm官網有許多套件與套件安裝指令可供查詢,大家可以多加善用。

輸入 「 xmlhttprequest」 或 「 w3c-xmlhttprequest」。

建立一個Line.js檔案,輸入以下程式碼。
var Token = "你的Token";
var LineNotifyURL = "https://notify-api.line.me/api/notify";
var PictureURL = "http://www.ccf.org.tw/new/endpoverty/images/product/product-pic1.jpg";
var strMessage = "message=" + "傳網頁圖檔測試 家扶娃娃撲滿 ~!@#$%^*()1234567890ABCabc";   
var strStickerPackageId  ="stickerPackageId=" + "1";
var strStickerId  ="stickerId=" + "106";
var strImageThumbnail = "imageThumbnail=" + PictureURL;
var strImageFullsize = "imageFullsize=" + PictureURL;
var strAllMessage = strMessage + "&" + strImageThumbnail + "&" + strImageFullsize + "&" + strStickerPackageId + "&" + strStickerId;

var XMLHttpRequest = require("w3c-xmlhttprequest").XMLHttpRequest;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
    if (xhttp.readyState === 4) {
        console.log(xhttp.responseText);
        console.log(xhttp.status);
    }
};            

xhttp.open('POST', LineNotifyURL, true);
xhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhttp.setRequestHeader('Authorization', 'Bearer ' + Token);
xhttp.send(strAllMessage);
第11行程式碼:「 w3c-xmlhttprequest」可換成「 xmlhttprequest」。

在「 Node.js command prompt 」執行
node Line.js

執行結果:

聰明的你是否有看出什麼問題了,對! 中文傳送出現亂碼,筆者一開始以為是JavaScript編碼問題,試了escape、encodeURI、encodeURIComponent函數還是沒能解決,最後找到解決的方法就是將檔案從ANSI格式轉為UTF-8格式,這樣就可以讓 Line Notify 收到正常的中文字。

執行結果:

參考資料: