目录:

1.1 cors跨域请求介绍返回顶部

  1、cors是什么  

      1. 随着技术的发展,现在的浏览器可以支持主动设置从而允许跨域请求,即:跨域资源共享(CORS,Cross-Origin Resource Sharing)

      2. 其本质是设置响应头,使得浏览器允许跨域请求。

  2、简单请求必须满足的两个条件(不满足就是 复杂请求)

      1. 条件1: 请求方式:HEAD、GET、POST

      2. 条件2: 请求头信息:

          Accept
          Accept-Language
          Content-Language
          Last-Event-ID
          Content-Type 对应的值是以下三个中的任意一个
              application/x-www-form-urlencoded
              multipart/form-data
              text/plain

  3、简单请求和非简单请求的区别

      简单请求    :一次请求
      非简单请求 :两次请求,在发送数据之前会先发一次请求用于做“预检”,只有“预检”通过后才再发送一次请求用于数据传输

  4、关于“预检”

      1. 请求方式:OPTIONS
      2. “预检”其实做检查,检查如果通过则允许传输数据,检查不通过则不再发送真正想要发送的消息
      3. 如何“预检”

          1) 如果复杂请求是PUT等请求,则服务端需要设置允许某请求,否则“预检”不通过
              Access-Control-Request-Method
          2) 如果复杂请求设置了请求头,则服务端需要设置允许某请求头,否则“预检”不通过
              Access-Control-Request-Headers

1.2 使用tornado实现 复杂请求返回顶部

  1、说明

      1. 由于复杂请求时,首先会发送“预检”请求,如果“预检”成功,则发送真实数据。

      2. “预检”请求时,允许请求方式则需服务器设置响应头:Access-Control-Request-Method
      3. “预检”请求时,允许请求头则需服务器设置响应头:Access-Control-Request-Headers
      4. “预检”缓存时间,服务器设置响应头:Access-Control-Max-Age

  2、tornado测试cors步骤

      1. 创建两个tornado项目: tom_tornado(客户端域)、jack_tornado(服务端域)

      2、修改C:\Windows\System32\drivers\etc 路径下的 hosts文件,添加两条hosts记录

          127.0.0.1 tom.com
          127.0.0.1 jack.com

      3、在http://tom.com:8000/get_date 的get_date.html文件通过ajax向 http://jack.com:8888/index 获取数据

      4、创建 tom_tornado项目(客户端域)

import tornado.ioloop
import tornado.web class MainHandler(tornado.web.RequestHandler):
def get(self):
self.set_header('Access-Control-Allow-Origin', "")
self.render('get_data.html') settings = {
'template_path': 'template',
'static_path': 'static',
'static_url_prefix': '/static/',
} application = tornado.web.Application([
(r"/get_date", MainHandler),
], **settings) if __name__ == "__main__":
application.listen(8000)
print('http://tom.com:8000/get_date')
tornado.ioloop.IOLoop.instance().start()

app.py

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<p>
<input type="submit" onclick="XmlSendRequest();" />
</p> <p>
<input type="submit" onclick="JqSendRequest();" />
</p> <script type="text/javascript" src="/static/jquery-1.12.4.js"></script>
<script>
function XmlSendRequest(){
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if(xhr.readyState == 4) {
var result = xhr.responseText;
console.log(result);
}
};
xhr.open('GET', "http://jack.com:8888/index", true);
xhr.send();
} function JqSendRequest(){
$.ajax({
url: "http://jack.com:8888/index",
type: 'GET',
dataType: 'text',
success: function(data, statusText, xmlHttpRequest){
console.log(data);
}
})
}
</script>
</body>
</html>

get_data.html

      5. 创建 jack_tornado项目(服务端域)

import tornado.ioloop
import tornado.web
import json class IndexHandler(tornado.web.RequestHandler):
def get(self):
self.set_header("Access-Control-Allow-Origin", "*")
self.set_header("Access-Control-Allow-Headers", "x-requested-with") # 允许请求头则需服务器设置响应头
self.set_header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS') # 允许请求方式则需服务器设置响应头
# self.set_header('Access-Control-Max-Age', 10) # “预检”缓存时间,服务器设置响应头
self.write('{"status": true, "data": "seven"}') settings = {
'template_path': 'views',
'static_path': 'static',
'static_url_prefix': '/static/',
} application = tornado.web.Application([
(r"/index", IndexHandler),
], **settings) if __name__ == "__main__":
application.listen(8888)
print('http://jack.com:8888/index')
tornado.ioloop.IOLoop.instance().start()

app.py

1.3 Django中使用django-cors-headers解决跨域问题返回顶部

  1、安装django-cors-headers 实现cors

      1. 安装django-cors-headers插件: pip install django-cors-headers

      2. 使用时在对应的Django项目settings.py中做以下修改:

#1、指定允许的hosts,否则通过 http://jack.com:8888/index/ 无法访问jack_django程序
ALLOWED_HOSTS = ['*'] #2、将corsheaders 注册到app中
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'corsheaders',
'app01',
] #3、将下面两条添加到中间件重
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
] #4、配置 django-cors-headers 中的参数
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_ALLOW_ALL = True
CORS_ORIGIN_WHITELIST = (
'*',
) CORS_ALLOW_METHODS = (
'DELETE',
'GET',
'OPTIONS',
'PATCH',
'POST',
'PUT',
'VIEW',
) CORS_ALLOW_HEADERS = (
'XMLHttpRequest',
'X_FILENAME',
'accept-encoding',
'authorization',
'content-type',
'dnt',
'origin',
'user-agent',
'x-csrftoken',
'x-requested-with',
'Pragma',
)

settings.py

   2、使用代码简单测试

      1. 创建一个tornado项目和一个Django项目: tom_tornado(客户端域:tornado项目)、jack_django(服务端域:Django项目)

      2、修改C:\Windows\System32\drivers\etc 路径下的 hosts文件,添加两条hosts记录

          127.0.0.1 tom.com
          127.0.0.1 jack.com

      3、在http://tom.com:8000/get_date 的get_date.html文件通过ajax向 http://jack.com:8888/index 获取数据

      4、创建 tom_tornado项目(客户端域)

import tornado.ioloop
import tornado.web class MainHandler(tornado.web.RequestHandler):
def get(self):
self.set_header('Access-Control-Allow-Origin', "")
self.render('get_data.html') settings = {
'template_path': 'template',
'static_path': 'static',
'static_url_prefix': '/static/',
} application = tornado.web.Application([
(r"/get_date", MainHandler),
], **settings) if __name__ == "__main__":
application.listen(8000)
print('http://tom.com:8000/get_date')
tornado.ioloop.IOLoop.instance().start()

app.py

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<p>
<input type="submit" onclick="XmlSendRequest();" />
</p> <p>
<input type="submit" onclick="JqSendRequest();" />
</p> <script type="text/javascript" src="/static/jquery-1.12.4.js"></script>
<script>
function XmlSendRequest(){
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if(xhr.readyState == 4) {
var result = xhr.responseText;
console.log(result);
}
};
xhr.open('GET', "http://jack.com:8888/index/", true);
xhr.send();
} function JqSendRequest(){
$.ajax({
url: "http://jack.com:8888/index/",
type: 'POST',
dataType: 'text',
success: function(data, statusText, xmlHttpRequest){
console.log(data);
}
})
}
</script>
</body>
</html>

get_data.html

      5. 创建 jack_django项目(服务端域)

        注:为避免端口冲突,主动修改jack_django项目监听端口为:8888

from django.shortcuts import render,HttpResponse
import json def index(request):
if request.method == 'get':
return HttpResponse(json.dumps({'name':'jack'}))
else:
return HttpResponse(json.dumps({'name': 'jack222'}))

views.py

#1、指定允许的hosts,否则通过 http://jack.com:8888/index/ 无法访问jack_django程序
ALLOWED_HOSTS = ['*'] #2、将corsheaders 注册到app中
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'corsheaders',
'app01',
] #3、将下面两条添加到中间件重
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
] #4、配置 django-cors-headers 中的参数
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_ALLOW_ALL = True
CORS_ORIGIN_WHITELIST = (
'*',
) CORS_ALLOW_METHODS = (
'DELETE',
'GET',
'OPTIONS',
'PATCH',
'POST',
'PUT',
'VIEW',
) CORS_ALLOW_HEADERS = (
'XMLHttpRequest',
'X_FILENAME',
'accept-encoding',
'authorization',
'content-type',
'dnt',
'origin',
'user-agent',
'x-csrftoken',
'x-requested-with',
'Pragma',
)

settings.py

08: CORS实现跨域请求的更多相关文章

  1. Django使用jsonp和cors解决跨域请求问题

    1.使用jsonp的方式解决跨域请求的问题 我启动两个django项目,然后使用的端口不一样,在项目1中通过ajax发请求给项目2,然后接受项目2发送过来的数据 先看项目1的ajax的代码 $(&qu ...

  2. 利用CORS实现跨域请求(转载)

    跨域请求一直是网页编程中的一个难题,在过去,绝大多数人都倾向于使用JSONP来解决这一问题.不过现在,我们可以考虑一下W3C中一项新的特性--CORS(Cross-Origin Resource Sh ...

  3. Java利用cors实现跨域请求

    由于ajax本身实际上是通过XMLHttpRequest对象来进行数据的交互,而浏览器出于安全考虑,不允许js代码进行跨域操作,所以会警告 网站开发,在某些情况下需要用到跨域. 什么是跨域? 跨域,指 ...

  4. [转] 利用CORS实现跨域请求

    [From] http://newhtml.net/using-cors/ 跨域请求一直是网页编程中的一个难题,在过去,绝大多数人都倾向于使用JSONP来解决这一问题.不过现在,我们可以考虑一下W3C ...

  5. 利用CORS实现跨域请求--转

    原文地址:http://newhtml.net/using-cors/ 跨域请求一直是网页编程中的一个难题,在过去,绝大多数人都倾向于使用JSONP来解决这一问题.不过现在,我们可以考虑一下W3C中一 ...

  6. SpringBoot:CORS处理跨域请求的三种方式

    一.跨域背景 1.1 何为跨域? Url的一般格式: 协议 + 域名(子域名 + 主域名) + 端口号 + 资源地址 示例: https://www.dustyblog.cn:8080/say/Hel ...

  7. Django中使用CORS实现跨域请求(转)

    原文:https://blog.csdn.net/zizle_lin/article/details/81381322 跨域请求: ​    请求url包含协议.网址.端口,任何一种不同都是跨域请求. ...

  8. Django中使用CORS实现跨域请求

    跨域请求: ​    请求url包含协议.网址.端口,任何一种不同都是跨域请求. 1.安装cors模块 pip install django-cors-headers2.添加应用 INSTALLED_ ...

  9. SpringBoot配置Cors解决跨域请求问题

    一.同源策略简介 同源策略[same origin policy]是浏览器的一个安全功能,不同源的客户端脚本在没有明确授权的情况下,不能读写对方资源. 同源策略是浏览器安全的基石. 什么是源 源[or ...

随机推荐

  1. Python3.6.3中,functools似乎不能用

    用pip install安装时报编码错误: return s.decode(sys.__stdout__.encoding) UnicodeDecodeError: 'utf-8' codec can ...

  2. iOS钱包卡券开发(往钱包里面加自己的卡券)

    参考文章 https://blog.csdn.net/sz_vcp2007/article/details/60762349 https://blog.csdn.net/eqera/article/d ...

  3. Circular reference 循环引用 第二联系人

    A circular reference is a series of references where the last object references the first, resulting ...

  4. 学习计划 mysql explain执行计划任务详解

    我们在之前已经找到了需要优化的SQL,但是怎么知道它的那些方面需要优化呢? explain就是为了这个使用的. explain显示了 mysql 如何使用索引来处理select语句以及连接表.可以帮助 ...

  5. 【make install】自定义安装目录,添加动态链接库 【--prefix】 【ldconfig】 【LD_LIBRARY_PATH】

    怎么卸载make install安装的软件? https://www.zhihu.com/question/20092756 怎么指定安装目录以及对应的添加动态库的方法 linux库在不指定安装路径时 ...

  6. 洛谷P3966 单词 [TJOI2013] AC自动机

    正解:AC自动机 解题报告: 传送门! 先来提供一个40pts错解QAQ 首先看到这题就会想到AC自动机板子题2鸭!然后就照着那题的套路打一下,随便改一点儿,简单来说就是每次经过一个节点都要++,然后 ...

  7. 大数据智能SOC解决方案

  8. sql执行顺序与性能优化小技巧(一)

    关于sql条件匹配对执行效率影响测试 首先,创建一个标量函数create function ff_test() returns int as begin declare @i int=0 while( ...

  9. 利用compass制作雪碧图

    compass是什么?是sass一款神奇插件,具体教程,我还是推荐阮一峰sass,compass教程,简单清晰明了. 用ps制作雪碧图,工作效率太低了.用compass来制作,方便很多.下图的用com ...

  10. servlet输出请求头

    1.参考 Enumeration headerNames = req.getHeaderNames(); while(headerNames.hasMoreElements()) { String h ...