现象: 在ajax访问web后端获取信息时,报错如下 Access to XMLHttpRequest at 'http://192.167.3.81:12345/stat/' from origin 'http://192.167.3.81:8888' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. 原因: ajax跨域涉及安全问题,需要针对跨域做特殊调整 方法: 原ajax中获取信息数据类型为json,跨域需要使用jsonp作为跨域访问的数据类型 原ajax js代码:
$.ajax({
type: "GET",
url: ins.server.statUrl,
contentType: 'application/json;charset=utf-8',
dataType: "json",
timeout: 1000,
success: function (result) {
console.error("success");
console.error(result)
ins.manager.map.charts(JSON.parse(result))
},
error: function (result) {
console.error("error");
console.error(result);
}
});
更改后的ajax js 代码:
$.ajax({
type: "GET",
url: ins.server.statUrl,
contentType: 'application/json;charset=utf-8',
dataType: "jsonp",
jsonp: "callback",
jsonpCallback:"jsonp_callback",
crossDomain: true,
timeout: 1000,
success: function (result) {
console.error("success");
console.error(result)
ins.manager.map.charts(JSON.parse(JSON.stringify(result)))
},
error: function (result) {
console.error("error");
console.error(result);
}
});
jsonp数据在使用是需要设置jsonp jsonpCallback 两个属性, 这样ajax在跨域访问时,会自动在基础url上增加查询参数,完整的url如下: http://192.167.3.81:12345/stat/?callback=jsonp_callback&_=1598190040288
web后端需要做出jsonp的特殊处理:
class StatisticsHandler(tornado.web.RequestHandler):
def get(self):
try:
。。。
jsonp_callback = self.get_query_arguments("callback")
if not jsonp_callback:
self.write(json.dumps(g_stat_map_sorted))
else:
self.write("{0}({1})".format(jsonp_callback[0], json.dumps(g_stat_map_sorted)))
self.set_header("Access-Control-Allow-Origin", "*")
self.set_header('Access-Control-Allow-Headers', 'x-requested-with')
self.set_header('Access-Control-Allow-Methods', 'GET')
如图所示:
针对jsonp做做特殊处理,通过jsonp_callback = self.get_query_arguments("callback")获取查询参数中"callback"对应的value
注意 self.get_query_arguments返回的类型是一个list,如果没有查询参数中没有"callback"这个key,则返回[]
所以当域内访问时,则无需对返回数据进行特殊处理
当跨域访问时,需要返回jsonp类型的数据,拼接方法如代码所示
并且还需要设置跨域消息header
self.set_header("Access-Control-Allow-Origin", "*") self.set_header('Access-Control-Allow-Headers', 'x-requested-with') self.set_header('Access-Control-Allow-Methods', 'GET')