解决问题的灵感来自于:https://segmentfault.com/a/1190000012469713
情景一:通过get请求.NET后端获取数据
今天使用ajax跨域请求获取数据,但是报错cors
$.ajax({
url: "",
type: "",
contentType: "",
dataType: "json",
success: function (data) {}
})
我尝试多遍后发现,当type为Get,contentType为application/x-www-form-urlencoded、 multipart/form-data、text/plain时,可以获取到数据,.NET后端设置只接受get,所有没有试post请求
浏览器将CORS请求分成两类:简单请求(simple request)和非简单请求(not-so-simple request)。只要同时满足以下两大条件,就属于简单请求。
- 请求方法是以下三种方法之一:HEAD,GET,POST
-
HTTP的头信息不超出以下几种字段:
- Accept
- Accept-Language
- Content-Language
- Last-Event-ID
- Content-Type(只限于三个值application/x-www-form-urlencoded、 multipart/form-data、text/plain)
凡是不同时满足上面两个条件,就属于非简单请求。
情景二:Post请求php后端添加数据
$.ajax({
url: "http://api-crm.com:8084/ctrl/ctrl.php?path=bcqz/keyword/keywordAdd.php",
type: "Post",
data:params,
contentType: "application/json",
dataType: "json",
success: function (data) {
debugger
if (data.IsSuccess) {
expand_total++
$("#totals_expand").text( expand_total);
$(".word_list").append("<span class='ch_index_"+index+"'>"+keywordName+" <small onclick='removeKeyword(\""+keywordName+"\",\""+index+"\")'>×</small></span>");
$("#table tbody").children().eq(index*1)
.children(".s_confirm_btn").removeClass("s_confirm_btn").addClass("s_cancle_btn")
.html("<span onclick='removeKeyword(\""+keywordName+"\",\""+index+"\")'>取消 </span>");
} else {
return false;
}
}
});
此时直接请求会报错 :No 'Access-Control-Allow-Origin' header is present on the requested resource,并且net::ERR_FAILED
解决方法:在被请求的php文件上方添加
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept');