前段時間做手機WebAPP, 但開發人員習慣在瀏覽器上先調試基本功能, 但這裏就出現了跨域請求問題
當然如果你自己寫服務, 自己寫WebAPP 都是localhost 就不會跨域, 而且發佈到手機上也不會跨域
關鍵來了!!!!
1. 先要確保你的js寫的是對的
$.ajax({
url: url3,
data: JSON.stringify({userName:uid,userPass:pwd}),
contentType:"application/json; charset=utf-8",
type:"POST",
crossDomain: true,
dataType: 'json',
success: function (data) {
},
error: function (xhr, textStatus, errMsg) {
}
});
2. 確保你的服務支持OPTION 請求格式, 因爲Jquery 跨域請求好像會請求兩次, 第一次OPTION, 第二次POST , 所以你的Method上面應該寫 * ,而不是POST
3. 你的web.config 的 system.webServer 節點需要增加跨域響應支持
<httpProtocol>
<customHeaders>
<addname="Access-Control-Allow-Origin"value="*" />
<addname="Access-Control-Allow-Headers"value="Content-Type" />
<addname="Access-Control-Allow-Methods"value="GET, POST,PUT, DELETE, OPTIONS" />
</customHeaders>
</httpProtocol>
4.這個不知道是不是必須的, 需要在system.serviceModel 中的standardEndpoint增加
crossDomainScriptAccessEnabled="true"
本人花了6個小時才解決,希望其他人少走彎路
/// <summary>
/// 移動跨域請求,會請求兩次,第一次OPTIONS 空數據請求,爲了獲取是否允許跨域,第二次纔是帶數據請求,所以爲了避免程序上一些Bug,空請求時就直接返回,不需要經過業務處理.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Global_PreRequestHandlerExecute(object sender, EventArgs e)
{
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
Response.End();
}
}
/// 移動跨域請求,會請求兩次,第一次OPTIONS 空數據請求,爲了獲取是否允許跨域,第二次纔是帶數據請求,所以爲了避免程序上一些Bug,空請求時就直接返回,不需要經過業務處理.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Global_PreRequestHandlerExecute(object sender, EventArgs e)
{
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
Response.End();
}
}