前段时间做手机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();
}
}