Ajax Post Cross Domain 跨域請求 WCF RestFull,wcfrestfull
前段時間做手機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個小時才解決,希望其他人少走彎路