js Ajax跨域访问调用API(WCF)
首先要保证接口能够正常访问,OPTION请求很容易被限制,包括IIS 或防火墙等;
服务端(WCF)IIS配置:
<httpProtocol> <customHeaders> <add name="Access-Control-Allow-Origin" value="*" /> <add name="Access-Control-Allow-Credentials" value="true" /><!--可传入cookie--> <add name="Access-Control-Allow-Headers" value="*,x-requested-with,Authorization,Content-Type" /> <add name="Access-Control-Allow-Methods" value="GET,PUT,POST,OPTIONS" /> <add name="Access-Control-Max-Age" value="30" /> </customHeaders> </httpProtocol>
Js跨域调用代码,jquery jsonp的方式支持跨域,但不能带Header头文件;
//方式一 $.ajax({ url: 'http://xxx:8066/PublicService/GetData?', type: 'GET', beforeSend: function(xhr) { xhr.setRequestHeader("Authorization", "验证Token"); }, dataType: 'json', crossDomain: true, --async: "false", headers: { 'Content-Type': 'application/json;charset=utf8', 'Authorization': '验证Token' }, success: function(data) { console.log("sucess"); }, error: function(data) { console.log("error"); } }); //方式二:(需要引用axios.js) axios('http://xxx:8065/PublicService/GetData?', { method: 'GET', mode: 'no-cors', headers: { 'Access-Control-Allow-Origin': '*', 'Content-Type': 'application/json', 'Authorization': '验证Token', }, //withCredentials: true, credentials: 'same-origin', }).then(response => {})
如果上述方法还不行,需要在服务端添加:
//在Global.asax中添加 protected void Application_BeginRequest(object sender, EventArgs e) { if (HttpContext.Current.Request.HttpMethod == "OPTIONS") { Response.End(); } } //或 Rest服务类中添加 [ServiceContract] [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)] [JavascriptCallbackBehavior(UrlParameterName = "callback")]//jsoncallback public partial class PublicService : GlobalBaseWcfRest { // }
google浏览器和IE浏览器下调试状况可能会不一样;
//原生js ajax请求 //步骤一:创建异步对象 var ajax = new XMLHttpRequest(); //步骤二:设置请求的url参数,参数一是请求的类型,参数二是请求的url,可以带参数,动态的传递参数starName到服务端 ajax.open('get','http://xxx:8001/PublicService/GetData?ID=123'); ajax.setRequestHeader("Authorization","UserName=Token_Key"); //ajax.withCredentials = true; //步骤三:发送请求 ajax.send(); //步骤四:注册事件 onreadystatechange 状态改变就会调用 ajax.onreadystatechange = function () { if (ajax.readyState==4 &&ajax.status==200) { //步骤五 如果能够进到这个判断 说明 数据 完美的回来了,并且请求的页面是存在的 console.log(ajax.responseText);//输入相应的内容 } }};