目录:

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. 线程池和进程池的通用写法 ProcessPoolExecutor 和 ThreadPoolExecutor

    import time from comcurrent.futures import ThreadPoolExecutor,ProcessPoolExccoutor#这个方法可以用进程池或者线程池 d ...

  2. MySQL 重做日志文件

    一.innodb log的基础知识 · innodb log顾名思义:即innodb存储引擎产生的日志,也可以称为重做日志文件,默认在innodb_data_home_dir下面有两个文件ib_log ...

  3. 洛谷 P4201 设计路线 [NOI2008] 树形dp

    正解:树形dp 解题报告: 大概是第一道NOI的题目?有点激动嘻嘻 然后先放个传送门 先大概港下这题的题意是啥qwq 大概就是给一棵树,然后可以选若干条链把链上的所有边的边权变成0,但是这些链不能有交 ...

  4. IO流(10)复制多级文件夹

    import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.File;import ja ...

  5. Ubuntu 下Apache安装和配置

    在Ubuntu上安装Apache,有两种方式:1 使用开发包的打包服务,例如使用apt-get命令:2 从源码构建Apache.本文章将详细描述这两种不同的安装方式. 方法一:使用开发包的打包服务—— ...

  6. Andrew Ng-ML-第十五章-降维

    1.数据压缩 数据压缩不仅能够减小存储空间,并且能够加速学习算法.那么什么是数据压缩呢?下面给出了一个简单的例子: 图1.数据压缩的概念 举了两个例子,一个是横轴x1是厘米,纵轴特征x2是英尺,这明显 ...

  7. 【java】System.out重定向到文件,并重定向会console上

    重定向到文件: System.setOut(new PrintStream(new File("data\\train.1.scale"))); 重定向回console: //把输 ...

  8. spark shuffle原理

    1.spark中窄依赖的时候不需要shuffle,只有宽依赖的时候需要shuffle,mapreduce中map到reduce必须经过shuffle 2.spark中的shuffle fetch的时候 ...

  9. 第一章SpringBoot入门

    一.简介 SpringBoot来简化Spring应用的开发,约定大于配置,去繁从简,just run就能创建一个独立的产品级别的应用. 背景: j2EE笨重的开发方法,繁多的配置,低下的开发效率,复杂 ...

  10. liferay笑傲江湖-API之参数的工具类(ParamUtil)

    public class ParamUtil { 036 037 public static boolean get( 038 HttpServletRequest request, String p ...