# 利用 Azure Function 解決JS CORS的問題 ###### tags: `Azure` ## 介紹 在使用js的時候,常常會因為CORS跨網域問題,只能存取同網域或是被迫架設後端伺服器去爬資料,在這邊介紹一種方法,可以利用Azure Function的無伺服器程式碼的方式,作為爬資料的跳板。 ## 價格比較 * Azure 前1百萬免費/每月 * GCP 前2百萬免費/每月 (勝) * AWS 前1百萬免費/每月 ## 入門文件比較 * Azure 中文有附圖 (勝) * GCP 英文 * AWS 英文有附圖 ## 支援語言 * Azure C# js Java * GCP Node.js Python * AWS Node.js js Python Java C# Go (勝) ## 建立方式 ### 簡短版流程 1. 在Azure開一個Function 2. 選擇http trigger的啟動方式 3. 撰寫可以爬東西的code (後面附上範例) 4. 開啟Azue的CORS 5. 放到js執行 ### 在Azure開一個Function 必須要註冊微軟帳號,方案可以選免費的F1,每個月可以用100萬次 ### 選擇http trigger的啟動方式 就是說網址被執行時才會啟動,其他常見的方式還包含計時器(排程)或是儲存體有新增東西(有傳檔案進來)...等等 ### 撰寫可以爬東西的code 剛開起來的原始範例是一個輸入name,回傳name的簡易程式 其實光這樣就可以看的出來有input,output的功能,如果手上已經有爬蟲程式的人,小幅度修改就能用了 ### 開啟Azue的CORS 在Azure Function 的 "平台功能",可以找到API,有CORS的設定選項 ![](https://i.imgur.com/MzsXLEs.png) 在 允許的原始 加上想要存取的來源,或是使用 * 萬用字元 ![](https://i.imgur.com/oWEbIP9.png) ### 放到 js 執行 前面的範例我是放在codepen,這邊就直接用codepen呈現 https://codepen.io/not0000/pen/yRVVPm?editors=0010 ## Azure Function 原始碼 ``` #r "Newtonsoft.Json" using System.Net; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Primitives; using Newtonsoft.Json; public static async Task<IActionResult> Run(HttpRequest req, ILogger log) { //從網址或post取得url string url = req.Query["url"]; string requestBody = await new StreamReader(req.Body).ReadToEndAsync(); dynamic data = JsonConvert.DeserializeObject(requestBody); url = url ?? data?.url; //利用 HttpWebRequest 去目標url取得資料 HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest; request.Method = "GET"; request.ContentType = "application/x-www-form-urlencoded"; request.Timeout = 30000; string result = ""; // 取得回應資料 using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { using (StreamReader sr = new StreamReader(response.GetResponseStream())) { result = sr.ReadToEnd(); } } //用log紀錄一下取回了什麼 //log.LogInformation(result); log.LogInformation("Finish"); return result != null ? (ActionResult)new OkObjectResult($"{result}") : new BadRequestObjectResult("no data"); } ``` ## 參考來源 ### 價格比較 Azure https://azure.microsoft.com/zh-tw/pricing/details/functions/ GCP https://cloud.google.com/functions/pricing (英文) AWS https://aws.amazon.com/tw/lambda/pricing/ ### 入門文件比較 * Azure https://docs.microsoft.com/zh-tw/azure/azure-functions/functions-create-first-azure-function * GCP https://cloud.google.com/functions/docs/quickstarts * AWS https://docs.aws.amazon.com/lambda/latest/dg/getting-started.html ### 支援語言 * Azure https://docs.microsoft.com/zh-tw/azure/azure-functions/supported-languages * GCP https://cloud.google.com/functions/docs/writing/ * AWS https://aws.amazon.com/tw/lambda/faqs/# ### CORS and Azure Functions http://blog.timwheeler.io/cors-and-azure-functions/ ### How can I parse a CSV string with Javascript, which contains comma in data? ms excel的雙引號"或是有換行的時候可能會遇到的問題 https://stackoverflow.com/questions/8493195/how-can-i-parse-a-csv-string-with-javascript-which-contains-comma-in-data