跨域问题
电脑版发表于:2018/11/22 11:13
跨域是指浏览器无法执行其他网站的脚本。(域名不同、子域名不同、端口不同、协议不同都属于跨域)
可通过前台后台两种方式解决跨域。前台:Jsonp(请求目标需可控),后台HttpClient。
一、JSONP
jsonp:为了便于客户端使用数据,逐渐形成了一种非正式传输协议,人们把它称作JSONP,该协议的一个要点就是允许用户传递 一个callback参数给服务端,然后服务端返回数据时会将这个callback参数作为函数名来包裹JSON数据,这样客户端就可以随 意定制自己的函数来自动处理返回数据了。
实现:
//请求目标的后台方法
public string WcfTest(string str)
{
if (!string.IsNullOrEmpty(str))
return "successCallback(1)";
else
return "successCallback(0)";
} //发出请求的的ajax
$.ajax({
url: 'http://localhost:14063/home/JsonpTest',
type: "get",
data: {str:"1"},
dataType: 'jsonp',
jsonpCallback: "successCallback",//根据返回的方法来定义,否则会出现返回成功不进入success的方法,只会进error方法
success: function (data) {
console.log('success');
console.log(data);
},
error: function (err) {
console.log('err');
console.log(err);
}
});注意:
1.jsonp方式发出的请求都会变成get请求。
2.设置jsonpCallback否则会出现无法进入success方法的情况,jsonpCallback课根据返回json方法的来自定义。
二、后台发出请求的方式,使用HttpClient
public async Task<string> Hps()
{
string url = "http://localhost:14063/home/JsonpTest";
HttpClientHandler handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.None };
using (HttpClient httpclient = new HttpClient(handler))
{
httpclient.BaseAddress = new Uri(url);
FormUrlEncodedContent content = new FormUrlEncodedContent(new Dictionary<string, string>()
{
{"username","1111"},
{"pwd","1234"},
}); //参数
Task<HttpResponseMessage> response = httpclient.PostAsync(url, content);
string responseString = await response.Result.Content.ReadAsStringAsync();
return responseString;
}
}