DIV CSS 佈局教程網

用一般處理常式做 JS 跨域代理的程式碼片段
編輯:關於JavaScript     

如果 JavaScript 需要多次跨域請求,比較推薦的做法是走後端代理:由前端呼叫同域的處理常式,再由它去請求目標站台。以下是一個 C# 的實作。

呼叫端

public string GetInfo(HttpContext context)
{
    string post = "a=XX&b=XX";
    return CreateHttpRequest("https://www.XXXX.com", post, "POST");
}

代理主體

#region 構造請求
/// <summary>
/// 構造並送出 HTTP 請求
/// </summary>
/// <param name="requestUrl">請求位址</param>
/// <param name="requestParam">請求參數</param>
/// <param name="requestMethod">請求方式</param>
public string CreateHttpRequest(string requestUrl, string requestParam, string requestMethod)
{
    try
    {
        System.Net.HttpWebRequest request =
            System.Net.HttpWebRequest.Create(requestUrl) as System.Net.HttpWebRequest;
        request.Method = requestMethod;

        byte[] bytes = System.Text.Encoding.UTF8.GetBytes(requestParam);
        request.ContentType = "application/x-www-form-urlencoded";
        request.ContentLength = bytes.Length;

        System.IO.Stream stream = request.GetRequestStream();
        stream.Write(bytes, 0, bytes.Length);

        System.Net.HttpWebResponse response =
            request.GetResponse() as System.Net.HttpWebResponse;
        System.IO.StreamReader sr =
            new System.IO.StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8);
        return sr.ReadToEnd();
    }
    catch (Exception)
    {
        return "";
    }
}
#endregion

幾個要注意的地方

編碼要一致。這裡固定用 UTF8 編碼請求與回應。如果目標站台用的是 GB2312 之類的編碼,StreamReader 的第二個參數必須跟著改,否則會拿到亂碼。

_contentType 與 Method 要對應。application/x-www-form-urlencoded 是表單提交用的;若目標是 JSON 介面,ContentType 要改成 application/json,同時不能用 GetRequestStream 寫字串的方式塞內容。

catch 全部例外不是好習慣。範例為了簡潔直接回傳空字串,正式環境至少該區分逾時、連線失敗與 HTTP 錯誤碼,並回傳有意義的狀態給前端,否則前端拿到空字串時無從判斷是沒資料還是出錯了。

代理要限制來源。開放式的代理等於把自己的伺服器當跳板,容易被拿來打其他站台。實務上應該白名單限制 requestUrl 的目標網域,並在入口处驗證呼叫方身分。

記得釋放資源。Stream 與 StreamReader 都應該用 using 包起來,避免連線沒有正常關閉而耗盡連線池。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved